【问题标题】:ios - force wait Alamofire response before returning in swift 4ios - 在 swift 4 中返回之前强制等待 Alamofire 响应
【发布时间】:2018-11-28 09:42:53
【问题描述】:

我有一种情况,我必须通过 OTP 代码在注册和登录时检查提供的手机号码。我在 Accounts 类中设置了所有内容,以便在 SignUpViewControllerSignInViewController 上重复使用它们。

ViewControllers我想先发送OTP,然后检查它是否从服务器响应发送到推送VerificationViewController,我使用Alamofire进行网络和SwiftyJSON解析JSON响应。现在让我们深入挖掘我的问题的核心:

这是我的SignUpViewController 课程的一部分

var acc: Accounts = Accounts()

@IBAction func signupAction(_ sender: Any) {
        if validateFields() {
            let fname = self.firstName.text!
            let lname = self.lastName.text!
            let pnum = self.phoneNumber.text!
            self.acc.setFirstName(fn: fname)
            self.acc.setLastName(ln: lname)
            self.acc.setPhoneNumber(pn: pnum)
            let result = self.acc.sendOTP()
            if (result) {
                let targetVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "signupVerfication") as? SignupVerficationViewController
                self.navigationController?.pushViewController(targetVC!, animated: true)
            }
            else {
                CustomComponents().alertWithTitle(title: "Error", message: "Unable to Verify Phone Number,Please Try again!", ViewController: self)
            }
        }
}

这是我的Accounts 课程的一部分

func sendOTP() -> Bool {
        let conf = APIConfig()
        var returnedResult = false
        conf.setURL(url: "patient/auth/send-totp")
        conf.setHeader(head: ["Content-Type": "Application/json"])
        conf.setBody(body: ["phone_number": self.phoneNumber])
        print(self.phoneNumber)
        Alamofire.request(conf.getURL(), method: .post, parameters: conf.getBody(), encoding: JSONEncoding.default, headers: conf.getHeader()).validate(statusCode: 200..<600).responseData { response in
            let status = response.response?.statusCode
            print(status!)
            let swiftJSONVar = JSON(response.result.value!)
            print(swiftJSONVar)
            if (status == 200) {
                returnedResult = true
            }
        }
        return returnedResult
    }

每当我运行应用程序时,我总是会收到警报作为输出,尽管如您所见,我通过在print(status!)print(swiftJSONVar) 打印响应来调试响应。打印的输出是200 作为状态码,我得到了其余的回复。

我一直在网上查看许多教程,例如:Grand Central Dispatch Tutorial for Swift 4Secure Coding With Concurrency in Swift 4 等等,但无法在我的代码块上实现 GCD。

我需要你的帮助吗?

【问题讨论】:

    标签: ios swift concurrency grand-central-dispatch


    【解决方案1】:

    sendOTP 方法的返回类型为Bool,它立即返回,因为Alamofire 请求是asynchronous,并且您在顶部设置了returnedResult false 的值,它立即返回而无需等待响应。响应来自 Alamofire 后,returnedResult 设置为 true,但无法通知调用者。由于从 sendOTP 方法返回 false,它显示错误警报。

    使用闭包而不是从 sendOTP 返回 bool,它接受 Bool 并返回 void

    func sendOTP(_ completion: @escaping (Bool) -> Void) {
        let conf = APIConfig()
        var returnedResult = false
        conf.setURL(url: "patient/auth/send-totp")
        conf.setHeader(head: ["Content-Type": "Application/json"])
        conf.setBody(body: ["phone_number": self.phoneNumber])
        print(self.phoneNumber)
        Alamofire.request(conf.getURL(), method: .post, parameters: conf.getBody(), encoding: JSONEncoding.default, headers: conf.getHeader()).validate(statusCode: 200..<600).responseData { response in
            let status = response.response?.statusCode
            print(status!)
            let swiftJSONVar = JSON(response.result.value!)
            print(swiftJSONVar)
            if (status == 200) {
                completion(true)
            } else {
                completion(false)
            }
        }
    }
    

    现在你可以打电话了

    self.acc.sendOTP { (result) in
        if result {
            //show vc
            let targetVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "signupVerfication") as? SignupVerficationViewController
            self.navigationController?.pushViewController(targetVC!, animated: true)
        } else {
            //show error alert
            CustomComponents().alertWithTitle(title: "Error", message: "Unable to Verify Phone Number,Please Try again!", ViewController: self)
        }
    }
    

    除了GCD 教程之外,我还推荐URLSessionAlamofire 教程,以了解iOS 中网络的工作原理。

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 2022-12-20
      • 2018-12-21
      • 1970-01-01
      • 2017-01-03
      • 2021-08-02
      • 2020-04-20
      • 2020-12-02
      • 2018-05-12
      相关资源
      最近更新 更多