Swift iOS : 訪問 https 伺服器

RecoReco發表於2019-02-20

使用URLSession可以訪問https伺服器。為了測試方便,省下自己編寫https伺服器的麻煩,可以使用一個網路服務叫做httpbin.org/ip,當訪問子URL時,它會返回一個json,格式為:

{
    origin = "221.237.156.243";
}複製程式碼

訪問https程式碼如下:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,URLSessionDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        foo()
        return true
    }
    func foo(){
        let task = URLSession.shared.dataTask(with: URL(string: "https://httpbin.org/ip")!) { (data, response, error) in
            if error != nil {
                print(error)
            } else {
                if let usableData = data {
                    do {
                        let json = try JSONSerialization.jsonObject(with: usableData, options:[])
                        print("json: (json)")
                    }
                    catch {
                        print("Error: (error)")
                    }
                }
            }
        }
        task.resume()
    }
}複製程式碼

相關文章