【发布时间】:2017-08-02 05:50:22
【问题描述】:
我对 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()
【问题讨论】:
-
这可能是由于 http 和 https。您是否在 info.plist 中添加了 NSAppTransportSecurity 密钥?
-
当您说不工作时,您是否没有获得 statusCode == 200 或者您无法解析或无法访问 API。您是否在 info.plist 中添加了 NSAppTransportSecurity 密钥?
-
不相关,但发送 GET 请求时根本不需要
URLRequest。只需传递 URL。并且不要在 Swift 中使用NSMutableURLRequest。有一个原生结构URLRequest。 -
您的代码目前看来是正确的,如果出现问题可能是在回调函数中,请提供回调函数的代码,如果可以的话。
-
另外请详细说明您遇到了什么问题?