我在使用 SWIFT 3 时遇到一个问题。当我使用具有两个不同 URL 的 rest api 时,出于某种原因,此 URL“http://sistemas2.laprensa.com.ni/LaPrensa/api/Beacons”无法正常工作,而此 URL“https://app.ccn.com.ni:8080/BeerWayNicaragua/api/BusinessType”正在工作。我检查了 JSON,没问题。请帮助我了解问题所在。
没有工作
let url = "http://sistemas2.laprensa.com.ni/LaPrensa/api/Beacons"
let requestURL: URL = URL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) {data,response,error in
if response != nil {
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do {
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)
callback((json as? [[String: AnyObject]])!)
}catch {
print("Error with Json: \(error)")
}
}
}
}
task.resume()
这是有效的,只是我更改了 URL。我不知道发生了什么。
let url = "https://app.ccn.com.ni:8080/BeerWayNicaragua/api/BusinessType"
let requestURL: URL = URL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) {data,response,error in
if response != nil {
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do {
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)
callback((json as? [[String: AnyObject]])!)
}catch {
print("Error with Json: \(error)")
}
}
}
}
task.resume()
最佳答案
尝试发出请求时阅读控制台日志。你会注意到提示。
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
解决方法如下
继续将以下键添加到您的 info.plist 文件中 vis source
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
或
来自 plist 编辑器。
关于ios - 使用 Rest API Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45452445/