使用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()
}
}复制代码