ios - Make instance wait until called functions are complete - Swift -


i apologise in advance if has been answered can tell title wasn't sure how describe issue , answer similar question found wasn't helpful.

i'm attempting make instance of "coupon" has properties loaded sql database after passing id database in init method.

my issue when call init method different viewcontroller class return instance default string values of "" data nsurlconnection hasn't been/decoded before returning viewcontoller.

im looking solution how make init method wait until fields loaded.

coupon class relevant properties:

var webdata: nsmutabledata?  var id: int var name: string = "" var provider: string = "" var details: string = "" 

coupon class relevant methods:

convenience init(id: int) {      self.init()     self.id = id      self.selectsql(id) //passes id server , returns other varibles  }     func selectsql(id: int) {      let url = nsurl(string: "http://wwww.website.php?id=\(id)") // acess php page     let urlrequest = nsurlrequest(url: url!)     let connection = nsurlconnection(request: urlrequest, delegate: self)  }  func connection(connection: nsurlconnection, didreceiveresponse response: nsurlresponse) {      webdata = nsmutabledata()  }  func connection(connection: nsurlconnection, didreceivedata data: nsdata) {      webdata?.appenddata(data)  }  func connectiondidfinishloading(connection: nsurlconnection) {      let result = nsjsonserialization.jsonobjectwithdata(webdata!, options: .allowfragments, error: nil) as? nsarray      let resultdict = result?[0] as? nsdictionary      if let dict = resultdict {          name = dict.objectforkey("name") as! string         provider = dict.objectforkey("provider") as! string         details = dict.objectforkey("details") as! string      } 

it not possible "wait sql finishing" , return init without blocking thread (synchronize), not want.

i suggest use factory method callback workaround it. this:

class coupon {     private var handler: ((coupon: coupon) -> ())?      class func createcoupon(id: int, completionhandler: ((coupon: coupon) -> ())?) {         let coupon = coupon(id: id)          // store handler in coupon         coupon.handler = completionhandler     }      //...      func connectiondidfinishloading(connection: nsurlconnection) {          //...setup coupon properties         handler?(coupon: self)         handler = nil     } } 

then can create , use coupon this:

coupon.createcoupon(1, completionhandler: { (coupon) -> () in     // thing "inited" coupon }) 

of course, need consider situation of connection failed server, , maybe call handler error, not present in current code.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -