使用 Alamofire 从 API 抓取数据时出错 [英] Error when grabbing data from API using Alamofire
问题描述
在尝试使用 Alamofire 从 Internet 访问 API 时,任何人都知道如何处理此错误.奇怪的是,我对其他 API 使用了相同的函数,它们似乎工作得很好,但不是这个.
Anyone know what to do with this error when trying to access an API from the internet using Alamofire. The strange thing is I have used the same function for other API's and they seem to work perfectly fine but not this.
API 是:
这里是错误:
Optional(Error Domain=NSURLErrorDomain Code=-1022 "资源可以未加载,因为应用传输安全策略要求使用安全连接."用户信息={NSUnderlyingError=0x6000004496c0 {错误域=kCFErrorDomainCFNetwork 代码=-1022 "(null)"},NSErrorFailingURLStringKey=http://minecraftpocket-servers.com/api/?object=servers&element=voters&key=833gowl7nz7jyqaqx96dagqzamn431yr9h&month=current&format=json&limit=10,NSErrorFailingURLKey=
Optional(Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x6000004496c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://minecraftpocket-servers.com/api/?object=servers&element=voters&key=833gowl7nz7jyqaqx96dagqzamn431yr9h&month=current&format=json&limit=10, NSErrorFailingURLKey=http://minecraftpocket-servers.com/api/?object=servers&element=voters&key=833gowl7nz7jyqaqx96dagqzamn431yr9h&month=current&format=json&limit=10, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.})
这是我要调用的函数.
func getAPIData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
let dataJSON : JSON = JSON(response.result.value!)
self.updateLabels(json: dataJSON)
print("Success!")
} else {
print("Error: Could not get data.")
print("Error: ", response.error)
}
}
}
推荐答案
发生这种情况是因为您使用的不是安全站点 (https),而是 http.
That happens because you are not using a secure site(https), but a http.
将此添加到您的 info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
这篇关于使用 Alamofire 从 API 抓取数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!