ios - Put a value out of a http request in swift -


to create uitableview have initialize number of rows, , in case depends on httprequest (sent framework httpswift). problem can't output number on return of request

request.get("/media/", parameters: nil, completionhandler:{     (response: httpresponse) in         if let err = response.error {             println("error: \(err.localizeddescription)")             return //also notify app of failure needed         }         if let data = response.responseobject as? nsdata {             let str = nsstring(data: data, encoding: nsutf8stringencoding)             var user = medias(jsondecoder(data))             var nbrows:int = user.medias.count         } })  println(nbrows) //nbrows don't have value out of request  func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {     return nbrows } 

the problem request performed in background thread , execution continues sequentially. when println(nbrows) nbrows variable not updated request has not been made yet or being made.

so fix this, make nbrows global variable , reload tableview when variable set.

use following code:

request.get("/media/", parameters: nil, completionhandler: {(response: httpresponse) in             if let err = response.error {                 println("error: \(err.localizeddescription)")                 return //also notify app of failure needed             }             if let data = response.responseobject as? nsdata {                 let str = nsstring(data: data, encoding: nsutf8stringencoding)                 //println(str)                 var user = medias(jsondecoder(data))                 self.nbrows = user.medias.count   // make nbrows globalvariable                 println(nbrows)                 // need update tableview in main thread                 dispatch_async(dispatch_get_main_queue(), {                     // reload tableview                     self.tableview.reloaddata()                 })             }         })  func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {     return nbrows } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -