ios - How would I create a callback around an XML request? -
i've been trying understand how callbacks work in swift. i've gone on quite few examples (like one) have helped me better understand callbacks, haven't had luck in implementing one.
i have function accepts url, downloads xml data web api , parses objects. @ same time have uilabel waiting data xml request.
below partial example of function i'd set callback. sake of clarity assume returns single data point which assigned uilabel later:
xmlutility.swift
// global var weekforecasts = [dayforecast]() class xmlutility { func retrievedatafromxml(myurl: string) { if let url = nsurl(string: myurl) { if let data = nsdata(contentsofurl: url) { var error: nserror? var cleaneddata = filterdata(data) if let doc = aexmldocument(xmldata: cleaneddata, error: &error) { //... work parsing xml //// day in date { //... work assigning values ///// weekforecasts.append(thisday) } } } }
the problem occurs in viewcontroller... have uilabels waiting values xml data request. when viewcontroller loads, xml hasn't processed yet , label failed receive value.
here's simplified example of doing in viewcontroller:
viewcontroller.swift
@iboutlet weak var currenttemperaturelabel: uilabel! override func viewdidload() { super.viewdidload() currenttemperaturelabel.text = // value out of [dayforecasts] }
i understand why case, , have novice understanding of how solve problem. believe need use callback but, based on examples have seen far, not sure how implement one.
my question:
given example provided, how convert retrievedatafromxml
method callback. additionally, how call function viewcontroller access data.
any on appreciated!
func retrievedatafromxml(myurl: string, completion: ((array<dayforecast>) -> void)) { if let url = nsurl(string: myurl) { if let data = nsdata(contentsofurl: url) { var error: nserror? var cleaneddata = filterdata(data) var weekforecasts = [dayforecast]() //local variable if let doc = aexmldocument(xmldata: cleaneddata, error: &error) { //... work creating objects xml day in date { //... work assigning values ///// weekforecasts.append(thisday) } //pass local array completion block, takes //array<dayforecast> parameter completion(weekforecasts) } } } }
called
//in example called in viewdidload func viewdidload() { var urlstring = "urlstring" retrievedatafromxml(urlstring, {(result) -> void in //result weekforecasts //ui elements can updated on main thread, main //thread , update ui element on thread dispatch_async(dispatch_get_main_queue(), { self.currenttemperaturelabel.text = result[0] //or whatever index want return }) }) }
is question asking for?
Comments
Post a Comment