我在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並確定。請幫助解決問題。Consuming Rest API Swift 3
沒有工作
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。只需傳遞網址即可。並且不要在Swift中使用'NSMutableURLRequest'。有一個本地結構'URLRequest'。 – vadian