我想寫一個函數從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()
}
NSURLResponse代替NSHTTPURLResponse – AnthonyR