简体   繁体   中英

NSURLSession sometimes returns data but sometimes don't iOS 9 - Swift 2.0

I'm developing an application what's based on JSON objects requested from specified URL but sometimes (not every time) I get no result
Gonna show some code snippets that can help determining this simple (?) problem
I have an array called "Data" ( var Data:[String] = [] ) in my class MyTestClass and the following function:

func loadData(onComplete: ([String]) -> ()) {
        // Declaring a local array
        var Local:[String] = []

        // Preparing JSON request
        let address = "<URL goes here>"
        let url = NSURL(string: address)
        let request = NSURLRequest(URL: url!)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            if (data?.length > 0 && error == nil) {
                let responseData = data as NSData!

                if responseData == nil {
                    // Presenting some alert
                } else {
                    let jsonObject: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.MutableContainers)

                    if jsonObject == nil {
                        // Presenting some alert
                    } else {
                        let json: NSArray = jsonObject as! NSArray

                        for (var i = 0; i < json.count; i++) {
                            if let obj = json[i] as? NSDictionary {
                                if let m = obj["m"] as? String {
                                    if m != "Unknown" {
                                        Local.append(m)
                                    }
                                }
                            }
                        }

                        onComplete(Local)
                    }

                }
            } else if error != nil {
                NSLog("Error: %@", error!)
            }
        }

        // Starting task
        task.resume()
    }

In viewDidLoad() I'm doing the following:

// Loading data
loadData { (d) in
    for dat in d {
        self.Data.append(dat)
    }
}

I'm using this solution (the functions are 100% the same [CTRL+C / CTRL+V]) in every of my ViewControllers, my hierarchy is the following: Table1 -> Table2 -> Table3

Table1 works fine, has no problem, displays the results every time fine, Table2 works most of the time (sometimes very rarely displays no result) but Table3 goes crazy ~80% of the time.

I'm getting mad because of this thing happening to me, before iOS 9 I used synchronous calls and had no problems because it's a small application, but now I don't even know how to make it work with this session.dataTaskWithRequest... thing.

You need to use dispatch async and reload the data of the table view on completion of your loadData block

use dispatch async with dataTaskWithRequest

You should call tableView.reloadData() (from the main queue) the request is done, after you're done appending all of those strings to your array.

loadData { (d) in
    dispatch_async(dispatch_get_main_queue()) {
        for dat in d {
            self.Data.append(dat)
        }
        self.tableView.reloadData()
    }
}

For the record, it's excellent that you have retired the synchronous network calls. The synchronous calls may have been easy, but they can cause problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM