Alamofire网络提取的完成处理程序 [英] Completion handler for Alamofire network fetch
问题描述
我正在尝试创建一个函数,该函数将返回通过解析JSON创建的自定义对象列表。我正在使用AlamoFire下载内容。我写了这个函数,成功后创建了一个要返回的位置数组。但是,回报总是为零。我的代码如下:
I am attempting to create a function which will return a list of custom objects, created from parsing JSON. I am using AlamoFire to download the content. I have written this function which, on success, creates an array of locations to be returned. However, the returns are always nil. My code is below:
func fetchLocations() -> [Location]? {
var locations : [Location]?
Alamofire.request(.GET, myURL)
.responseJSON { response in
switch response.result {
case .Success(let data):
locations = createMapLocations(data)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
return locations
}
我非常肯定问题是功能在网络请求之前返回做完了。我是Swift的新手,不确定如何处理这个问题。任何帮助将不胜感激!
I am pretty positive the issue is that the functioning is returning before the network request is complete. I am new to Swift, and unsure how to handle this. Any help would be appreciated!
推荐答案
您可以阅读有关闭包/完成处理程序的更多信息 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures .html 或谷歌。
You can read more about closures/ completion handlers https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html or google.
func fetchLocations(completionHandler: (locations: [Location]?, error: NSError) -> ()) -> () {
var locations : [Location]?
Alamofire.request(.GET, myURL)
.responseJSON { response in
switch response.result {
case .Success(let data):
locations = createMapLocations(data)
completionHandler(locations, error: nil)
case .Failure(let error):
print("Request failed with error: \(error)")
completionHandler(locations: nil, error: error)
}
}
}
用法
fetchLocations(){
data in
if(data.locations != nil){
//do something witht he data
}else{
//Handle error here
print(data.error)
}
}
这篇关于Alamofire网络提取的完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!