How would I create a callback around an XML request?

空扰寡人 提交于 2019-12-07 15:32:40
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) {

                //... does some work creating objects from xml
                for day in date {

                   //... some work assigning values /////

                   weekForecasts.append(thisDay)

                }    
                //pass the local array into the completion block, which takes
                //Array<DayForecast> as its parameter
                completion(weekForecasts) 
            }
        }
    }  
}

called like

//in this example it is called in viewDidLoad
func viewDidLoad() {
    var urlString = "urlstring"
    retrieveDataFromXML(urlString, {(result) -> Void in
        //result is weekForecasts

        //UI elements can only be updated on the main thread, so get the main 
        //thread and update the UI element on that thread
        dispatch_async(dispatch_get_main_queue(), {
            self.currentTemperatureLabel.text = result[0] //or whatever index you want
            return
        })
    })
}

Is this what your question was asking for?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!