为什么NSHTTPURLResponse返回nil? NSURLSession,Swift 2.2
问题描述:
我想写一个函数从Web上的服务获取JSON,但其中一行(注释)不断返回零,我不知道为什么。任何帮助表示赞赏! :) 谢谢!!为什么NSHTTPURLResponse返回nil? NSURLSession,Swift 2.2
func parseJSON(long: CLLocationDegrees, lat: CLLocationDegrees) {
var longitude : String = "\(long)"
var latitude : String = "\(lat)"
longitude = longitude.substringToIndex(longitude.characters.indexOf(".")!)
latitude = latitude.substringToIndex(latitude.characters.indexOf(".")!)
print("\(latitude),\(longitude)")
let appId = "xyz" //Insert API Key
let urlString = "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&units=metric&appid=\(appId)"
let requestURL: NSURL = NSURL(string: urlString)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
//Keeps returning nil. No idea why.
if let httpResponse = response as? NSHTTPURLResponse {
print("Success!")
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
} else {
print("STATUSCODE=\(statusCode)")
}
}
}
task.resume()
}
答
func dataTaskWithRequest(_ request: NSURLRequest,
completionHandler completionHandler: (NSData?,
NSURLResponse?,
NSError?) -> Void) -> NSURLSessionDataTask
初始方法采用NSURLResponse
。这是所请求的URL的响应。 NSURLResponse
可以是任何类型的响应。
NSHTTPURLResponse
是NSURLResponse
的子类,只有在确定您的webservice使用HTTP协议对响应进行编码时,才能将您的响应转换为NSHTTPURLResponse
。否则,演员将永远返回nil
。
而且,我看到的是你正在使用WebService有使用的一些限制:
如何获得准确的API响应
1,不要更多的发送请求,然后每10 1次来自一个设备/一个API密钥的分钟数。通常情况下,天气并不会改变,因此经常使用 。
2使用服务器的名称作为api.openweathermap.org。请绝不使用 使用服务器的IP地址。
3以城市ID调用API而不是城市名称,城市坐标或邮编 代码。在这种情况下,您可以准确地为您的城市做出回应。
4免费帐户限制了容量和数据可用性。如果 你没有得到服务器的回应,不要试图立即重复你的 请求,但只能在10分钟后。此外,我们建议您存储 您以前的请求数据。
现在我想你的问题可能来自那里。
NSURLResponse代替NSHTTPURLResponse – AnthonyR