使用Alamofire和SwiftyJson从函数返回值

编程入门 行业动态 更新时间:2024-10-25 14:22:56
本文介绍了使用Alamofire和SwiftyJson从函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个返回信息菜单(基本上是菜单,menu_headers和项)的应用。我想要这样的东西:

I have an app that returns a menu of information (basically menus, menu_headers, and items). I'd like to have something like this:

EKMenu.getMenu(menu_id: Int)

这将返回一个菜单,但我想我需要在此处添加完成处理程序。

that would return a menu but I think I would need a completion handler in here.

我目前有:

class func getMenu(menu_id: Int){ //class func getMenu(menu_id: Int, completionHandler:(NSArray -> Void)){ let url="www.example/arc/v1/api/menus/\(menu_id)/mobile" Alamofire.request(.GET, url).responseJSON() { (_, _, data, _) in println("within menu request") var json=JSON(data!) var menu=EKMenu() menu.name=json["menu"]["name"].stringValue for (key, subJson) in json["menu"]["menu_headers"]{ EKMenu.processMenuHeaders(subJson) } // how would we return a value here ????? } } class func processMenuHeaders(menu_header: JSON){ let mh_name=menu_header["name"].stringValue println("mh_name: \(mh_name)") for (key, subJson) in menu_header["menu_headers"]{ EKMenu.processMenuHeaders(subJson) } }

但是我实际上如何在这里退货?我99%确信它是某种类型的完成处理程序,但是对于Swift和Alamofire来说,这是我的新手,我有点迷失了。我见过我不会能够在Swift中使用Alamofire返回值,但是知道其中某些值很快就会过期(例如,Swift 1.1)

but how do I actually return something here? I am 99% sure that it's some type of completion handler but, being new to Swift and Alamofire, I'm a bit lost. I've seen I won't be able to return a value with Alamofire in Swift but know that some of this is going out of date very quickly (ie Swift 1.1)

推荐答案

getMenu函数的完成处理程序示例,假设菜单是您要返回的值:

An example of a completion handler for your getMenu function, assuming menu is the value you want to "return":

class MenuManager { // the handler takes an EKMenu argument class func getMenu(menu_id: Int, completionHandler: (menu: EKMenu) -> ()) { let url="www.domain/arc/v1/api/menus/\(menu_id)/mobile" Alamofire.request(.GET, url).responseJSON() { (_, _, data, _) in println("within menu request") var json=JSON(data!) var menu=EKMenu() menu.name=json["menu"]["name"].stringValue for (key, subJson) in json["menu"]["menu_headers"]{ EKMenu.processMenuHeaders(subJson) } // wrap the resulting EKMenu in the handler completionHandler(menu) } } class func processMenuHeaders(menu_header: JSON){ let mh_name=menu_header["name"].stringValue println("mh_name: \(mh_name)") for (key, subJson) in menu_header["menu_headers"]{ EKMenu.processMenuHeaders(subJson) } } } MenuManager.getMenu(42, completionHandler: { menu in // here the handler gives you back the value println(menu) })

更多推荐

使用Alamofire和SwiftyJson从函数返回值

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

发布评论

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

>www.elefans.com

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