-2

I'm trying to get an array from the method down below. The method parseJSONResult returns an array, and I've checked that it does this correctly with a print and it absolutely does. The variable self.jobOpenings is an array property in the class. I have this variable because I want to use it after I've called doNetworking() in another class. However, .count gives me 0 if called outside the if httpResponse.statusCode == 200 statement. I hope I have given enough information for anyone to help me out, thanks.

func doNetworking() {
        dataTask?.cancel()
        let url = NSURL(string: "https://example.com/")
        let session = NSURLSession.sharedSession()
        dataTask = session.dataTaskWithURL(url!, completionHandler: {
            data, response, error in
            if let error = error {
                if error.code == -999 {
                    print(error)
                }   
            } else if let httpResponse = response as? NSHTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    let parsedData = self.parseJSONData(data!)
                    self.jobOpenings = self.parseJSONResult(parsedData!)
                    return
                }
            }
        })
        dataTask?.resume()
    }  
Rasmus
  • 241
  • 3
  • 19
  • `doNetworking` doesn't wait for the request to be completed. When you are checking `count` from another class, the request is still running so the value is obviously still zero. Read up about asynchronous calls and callbacks. – Sulthan Feb 12 '16 at 12:24
  • Possible duplicate of [Downloading JSON with NSURLSession doesn't return any data](http://stackoverflow.com/questions/35289389/downloading-json-with-nsurlsession-doesnt-return-any-data) – Eric Aya Feb 12 '16 at 12:43

1 Answers1

0

I think that if you call the .count method outside the if httpResponse.statusCode == 200 it would be 0 because of the return at the end of the if

When the if is executed the code after it, wouldn't be called

Roberto Frontado
  • 438
  • 5
  • 16