首页 > 解决方案 > 在 Swift 中按顺序执行任务

问题描述

我正在尝试验证登录并相应地从我的函数返回一个布尔值,但即使我使用异步方法,我的 return 语句也会在 Web 服务函数完成之前继续执行。我同时使用 Alamofire 和 SwiftyJSON。

我在下面附上我的代码。任何帮助,将不胜感激!

谢谢。

func checkUs (name: String, password: String)  -> Bool
    {

        bool authen = false
        DispatchQueue.global(qos: .userInitiated).async {

        let jsonDic : [String: String] = ["email": name, "pass": password]
        Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
                switch(response.result) {
                case .success(let sentJSON):
                    let gotJSON = JSON (sentJSON)
                    print (gotJSON[0]["status"].boolValue)
                    authen = gotJSON[0]["status"].boolValue
                case .failure(let err):
                    print(err)
                }

            print ("First ", authen)
        }
        }
        print ("Second", authen)

        return authen
        //return true

日志输出:

第二个假

第一个真

标签: iosswiftalamofireswifty-json

解决方案


您需要完成,Alamfire 也异步运行,不需要全局队列

func checkUs (name: String, password: String,completion: @escaping (_ status: Bool,_ err:Error?) -> Void) {

        bool authen = false

        let jsonDic : [String: String] = ["email": name, "pass": password]
        Alamofire.request("enter URL here", method: .post, parameters: jsonDic, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
                switch(response.result) {
                case .success(let sentJSON):
                    let gotJSON = JSON (sentJSON)
                    print (gotJSON[0]["status"].boolValue)
                    authen = gotJSON[0]["status"].boolValue
                     completion(authen,nil)
                case .failure(let err):
                    print(err)
                    completion(authen,err)
                }

            print ("First ", authen)

        }
        print ("Second", authen)

     }

//

像这样称呼它

self.checkUs(name: "endedName", password: "sendedPassword") { (status, error) in

    if let err = error {


    }
    else
    {

    }
}

推荐阅读