Alamofire网络提取的完成处理程序

编程入门 行业动态 更新时间:2024-10-12 10:23:11
本文介绍了Alamofire网络提取的完成处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个函数,该函数将返回通过解析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!

推荐答案

您可以阅读有关闭包/完成处理程序的更多信息 developer.apple/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures .html 或谷歌。

You can read more about closures/ completion handlers developer.apple/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网络提取的完成处理程序

本文发布于:2023-11-26 02:02:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632204.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序   网络   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!