ios - using JSON data in SWIFT UI controls -
i need use data json web service update controls in swift app. can data no problem, can't seem access ui controls within task block , can't json persist out of block. i've searched around , haven't found answer. here's test code. current result value1result has value inside task, nil outside. in advance.
var jsonresult:nsdictionary! var value1result:string! let task = nsurlsession.sharedsession().datataskwithurl(url!) { data, response, error in var error: nserror? jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.allowfragments, error: &error)! as! dictionary<string, anyobject> println(jsonresult) if let value1 = jsonresult["value1"] { println(value1) value1result = value1 as! string } } task.resume() self.textview1.text = value1result
you can use asynchronous block update main ui
dispatch_async(dispatch_get_main_queue()) { //update ui }
with code
let task = nsurlsession.sharedsession().datataskwithurl(url!) { data, response, error in var error: nserror? jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.allowfragments, error: &error)! as! dictionary<string, anyobject> println(jsonresult) if let value1 = jsonresult["value1"] { println(value1) dispatch_async(dispatch_get_main_queue()) { //update ui value1result = value1 as! string self.yourtextview.text = value1 as! string } } } task.resume()
Comments
Post a Comment