如何创建围绕XML请求的回调? [英] How would I create a callback around an XML request?
问题描述
我一直在试图理解回调在Swift中如何工作。我已经讨论了几个例子(喜欢这个)帮助我更好地理解回调,但我没有运气正确实现一个。
我有一个函数接受一个URL,从web api下载一些XML数据,然后将其解析为对象。同时,我有一个UILabel,它正在等待XML请求中的一些数据。
下面是我想设置的函数的一个部分示例与回调。为了清楚起见,只是假设它只返回单个数据点,稍后将分配给 UILabel :
XMLUtility .swift
// global
$ p>
var weekForecasts = [DayForecast]()
class XMLUtility {
func retrieveDataFromXML(myUrl:String){
如果let url = NSURL(string:myUrl){
if let data = NSData (contentsOfURL:url){
var error:NSError?
var cleansData = filterData(data)
如果let doc = AEXMLDocument(xmlData:cleansData,error:& error){
// ...一些工作解析xml ////
for day in date {
// ...一些工作分配值/////
weekForecasts.append(thisDay)
}
}
}
}
问题发生在我的ViewController ...我有一些UILabels正在等待来自XML数据请求的值。当ViewController加载时,XML尚未处理,标签未能接收到值。
这是一个简单的例子,我在我的ViewController中做的: / p>
ViewController.swift
@IBOutlet weak var currentTemperatureLabel:UILabel!
override func viewDidLoad(){
super.viewDidLoad()
currentTemperatureLabel.text = //我得到一个值的我的[DayForecasts]
}
我理解为什么会是这样,一个新手的了解如何解决问题。我相信我需要使用回调,但基于我所看到的例子,我不知道如何实现一个。
我的问题:
根据提供的示例,如何转换我的
retrieveDataFromXML
方法转换为回调。另外,如何从我的ViewController调用函数来访问数据。
任何帮助将非常感谢!
解决方案
func retrieveDataFromXML(myUrl:String,completion:((Array< DayForecast> - > Void)){
如果let url = NSURL(string:myUrl){
if let data = NSData(contentOfURL:url){
var error:NSError?
var cleansData = filterData(data)
var weekForecasts = [DayForecast]()//局部变量
如果let doc = AEXMLDocument(xmlData:cleansData,error:& error ){
// ...做一些工作从xml创建对象
for date in date {
// ...一些工作分配值// ///
weekForecasts.append(thisDay)
}
//将本地数组传递给完成块,它接受
// Array< ; DayForecast>作为其参数
完成(weekForecasts)
}
}
}
}
称为
//在此示例中,它在viewDidLoad
中调用func viewDidLoad(){
var urlString =urlstring
retrieveDataFromXML(urlString,{(result) - > Void in
//结果是weekForecasts
/ / UI元素只能在主线程上更新,所以获取主
//线程并更新该线程上的UI元素
dispatch_async(dispatch_get_main_queue(),{
self.currentTemperatureLabel。 text = result [0] //或任何您想要的索引
return
})
})
}
这是你的问题是什么?
I've been trying to understand how callbacks work in Swift. I've gone over quite a few examples (like this one) that have helped me to better understand callbacks, but I haven't had any luck in properly implementing one.
I have a function that accepts a URL, downloads some XML data from a web api and then parses it into objects. At the same time I have a UILabel that is waiting for some data from the XML request.
Below is a partial example of my function that I'd like to set up with a callback. For the sake of clarity just assume it only returns a single data point which which will be assigned to a 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) { //... does some work parsing xml //// for day in date { //... some work assigning values ///// weekForecasts.append(thisDay) } } } }
The problem occurs in my ViewController... I have some UILabels that are waiting for values from the XML data request. When the ViewController loads, the XML hasn't processed yet and the label failed to receive a value.
Here's a simplified example of what I am doing in my ViewController:
ViewController.swift
@IBOutlet weak var currentTemperatureLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() currentTemperatureLabel.text = // I get a value out of my [DayForecasts] }
I understand why this is the case, and I have a novice understanding of how to solve the problem. I believe I need to use a callback but, based on the examples I have seen so far, I am not sure how to implement one.
My question:
Given the example provided, how would I convert my
retrieveDataFromXML
method into a callback. Additionally, how do I call the function from my ViewController to access the data.Any help on this would be greatly 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) { //... 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?
这篇关于如何创建围绕XML请求的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!