0

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()

}
1
  • NSURLResponse instead of NSHTTPURLResponse Commented May 29, 2016 at 20:13

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.