Reputation: 3
I'm trying to write a function fetches JSON from a service on the web but one of the lines (commented) keeps returning nil and I have no idea why. Any help is appreciated! :) Thanks!!
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()
}
Upvotes: 0
Views: 534
Reputation: 3545
func dataTaskWithRequest(_ request: NSURLRequest,
completionHandler completionHandler: (NSData?,
NSURLResponse?,
NSError?) -> Void) -> NSURLSessionDataTask
The initial method takes an NSURLResponse
. This is the response of the requested URL. NSURLResponse
can be of any kind of response.
NSHTTPURLResponse
is a subclass of NSURLResponse
, you can cast your response to NSHTTPURLResponse
only if you are sure that your webservice encode responses using the HTTP protocol. Otherwise, the cast will always return nil
.
Also, I'm seeing that the Webservice that you are using has some restrictions of usage :
How to get accurate API response
1 Do not send requests more then 1 time per 10 minutes from one device/one API key. Normally the weather is not changing so frequently.
2 Use the name of the server as api.openweathermap.org. Please never use the IP address of the server.
3 Call API by city ID instead of city name, city coordinates or zip code. In this case you get precise respond exactly for your city.
4 Free account has limitation of capacity and data availability. If you do not get respond from server do not try to repeat your request immediately, but only after 10 min. Also we recommend to store your previous request data.
Now I'm thinking that your problem could come from there.
Upvotes: 1