我有一个问题 . Safari可以加载页面h ttp://ip-api.com/json
,但URLSession任务不能 . 这是viewDidLoad中的代码
let url = URL(string: "http://ip-api.com/json")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
print("this is the server response: \(response)")
if error != nil {
print("some error: \(error)")
} else {
if let urlContent = data {
print(urlContent)
}
}
})
task.resume()
控制台日志报告以下错误内容:
...一些错误:可选(错误域= NSURLErrorDomain代码= -1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo = {NSUnderlyingError = 0x60800005bc00 {错误域= kCFErrorDomainCFNetwork代码= -1022 "(null)"},NSErrorFailingURLStringKey = http://ip-api.com/json,NSErrorFailingURLKey = http://ip-api.com/json,NSLocalizedDescription =资源不能是因为App Transport Security策略需要使用安全连接而加载 . })
2 回答
有一个小错误!编辑plist项时,我在
<key>
和属性名之间留了一个空格,如下所示<key> NSAppTransportSecurity</key>
. 抱歉在你的info.plist文件中添加这个,
它会对你有用 .