ios - 在 Swift 中顺序执行任务

标签 ios swift alamofire swifty-json

我正在尝试验证登录并相应地从我的函数返回 bool 值,但即使我使用异步方法,我的 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

日志输出:

第二个错误
正确
第一个真实

最佳答案

您需要完成,而且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
    {

    }
}

关于ios - 在 Swift 中顺序执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257326/

相关文章:

ios - 台风不会注入(inject)普通的 NSObject 派生类

swift - Alamofire 4.1.0 警告

ios - Alamofire .dowload 占用大量内存(ios、swift)

ios - 我可以对一个 UITableViewDelegate 使用多个 segues 吗?

ios - AVAssetExportSession、可变格式配置文件、CABAC 和重构

iOS - 将 cocoapods 添加到项目后 git merge 冲突

ios - 架构 x86_64 iOS Swift 的重复符号

macos - 如何防止 Storyboard 打开窗口

swift - 我如何查看 Alamofire 请求?

ios - Oauth 失败后的 AlamoFire 重试请求