Returning a value from a function with Alamofire and SwiftyJson

℡╲_俬逩灬. 提交于 2019-11-28 01:32:48

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="https://www.domain.com/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)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!