I won't be able to return a value with Alamofire in Swift

前端 未结 3 519
别跟我提以往
别跟我提以往 2020-12-11 21:48

The current code I\'m having doens\'t seem to return anything, I can\'t find out what is causing the issue.

func getQuests(category: NSString, count: Int) -&         


        
3条回答
  •  执笔经年
    2020-12-11 22:50

    When doing asynchronous work inside a function, it is not possible to return the value as you would like to. Functions that have asynchronous parts in it usually let you pass in a "completion handler", which will get executed once the asynchronous task is complete.

    In your case, this would mean, you have to change your function "getQuests" like this for example:

    func getQuests(category: NSString, count: Int, completionHandler: (NSArray -> Void)) {
    
        Alamofire.request(.GET, apiUrlString, parameters: ["category": category, "count": count])
            .responseJSON { (request, response, json, error) in
                dispatch_async(dispatch_get_main_queue(), {
                    let quests = json as? NSArray
                    // pass the array of quests, or an empty array to your completionHandler
                    completionHandler(quests ?? [])
                })
        }
    }
    

    You can then call this function from somewhere and pass in the completion handler where you do something with the quests retrieved:

    getQuests("Easy", count: 5, completionHandler: {
        quests in
            println(quests)
        })
    

    Hope this gets you started.

提交回复
热议问题