简体   繁体   中英

Loading value in UITableViewController from async task

I have a problem trying to load a UITableViewController.

I have an async task that is called in the loadView method. This async task works well and results are returned as I expect.

The problem is, the app fail when trying to populate the TableView.

I suspect that it's due to the fact that my data are not completely loaded when the method are called.

Is there anyway to force the TableView to wait on my async task to be finished ?

The function that loads my data:

func loadNetInformations(){
    var postString: NSString = "info=all"

    HTTPGet("myurl", "POST", postString){
        (data: NSArray, error:String?)-> Void in
        if error != nil{
            println(error)
        }
        else{
            for value in data{
                var sService: NSString = "some value"

                var aContent: NSArray = value["Content"] as NSArray

                var sNumberCount: NSNumber = aContent.count

                self.aListeService.addObject(sService)
                self.aSizeOfDpt.addObject(sNumberCount)
                self.aContenuListes.addObject(aContent)

                self.bFinishLoading = true

            } // End for in HTTPGet
        } // End else in HTTPGet
    } // End HTTPGet

} // End LoadNet Information

My HTTPGet method is as following:

func HTTPSendRequest(request: NSMutableURLRequest,
callback: (NSArray, String?) -> Void){
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {

            callback (NSArray(), error.localizedDescription)
            println("error=\(error)")
            return
        }
        else{
            callback(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)! as NSArray, nil)

        }


    }
    task.resume()
}


func HTTPGet(url: String, requestMethod: String, postString: String, callback: (NSArray, String?) -> Void){
     var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = requestMethod
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    HTTPSendRequest(request, callback)
}

EDIT: Ok now I don't have the error anymore (I used a NSString as an NSInteger...) but it doesn't show anything

EDIT2: here's my JSON format in case it can help:

[
  {
    "CodeAbsence" : "6000", 
    "Content" : 
                [
                  {
                    "Init":"DAS",
                    "Nom":"Name",
                    "Prenom":"Firstname",
                    "IdAbsence":"619",
                    "TimbreusePresent":"O",
                    "TimbreuseHeure":"14:44",
                    "TimbreuseRaison":"0",
                    "TimbreuseDate":"",
                    "CodeAbsence":"6000",
                    "Telephone":"248"
                   },
                    ....
               ]
  },
   .......
 ] 

You need to reload the tableView to trigger a table update and you need to trigger it on the main UI thread.

        for value in data{
            var sService: NSString = "some value"

            var aContent: NSArray = value["Content"] as NSArray

            var sNumberCount: NSNumber = aContent.count

            self.aListeService.addObject(sService)
            self.aSizeOfDpt.addObject(sNumberCount)
            self.aContenuListes.addObject(aContent)

            self.bFinishLoading = true
            dispatch_async(dispatch_get_main_queue()) {
                 self.tableView.reloadData()
            } 
        }

When you perform an asynchronous operation on a background thread your callback is still going to run on the background thread, so always be sure to switch back to the main thread before performing any UI task.

I finally found what was the problem. It was coming from the use of viewDidLoad() instead of viewDidAppear() .

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