Swift Alamofire + Promise catching

馋奶兔 提交于 2019-12-07 12:27:16

问题


Folks, The following works except for the catch, xcode errors out with expected member name following '.'

Is this the proper way to promisify with PromiseKit?

All suggestions welcome! Thanks!

@IBAction func loginButtonTapped(sender: AnyObject) {
        let email = userEmail.text!
        let password = userPassword.text!

        func onSuccess(success:Bool, message:String, token: String) -> Promise<Void> {
            if success {
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
                NSUserDefaults.standardUserDefaults().synchronize()
                self.dismissViewControllerAnimated(true, completion: nil)
            } else {
                let myAlert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.Alert)
                let okAction = UIAlertAction(title: "Try Again", style: UIAlertActionStyle.Default, handler: nil)
                myAlert.addAction(okAction)
                self.presentViewController(myAlert, animated: true, completion: nil)
            }
            return Promise { resolve, reject in
                return resolve()
            }
        }

        func onFailure(error:NSError) -> Promise<Void> {
            return Promise { resolve, reject in
                return reject(error)
            }
        }

        Login(email, password: password).then(onSuccess).catch(onFailure)
    }


private func Login(email: String, password: String) -> Promise<(success:Bool, message:String, token: String)> {
    let parameters: [String: String] = [
        "username" : email,
        "password" : password
    ];
    let endpoint = "https://api.foo.bar/login"
    return Promise { resolve, reject in
        Alamofire.request(.POST, endpoint, parameters: parameters, encoding: .JSON)
            .validate()
            .responseJSON { (response) in
                guard response.result.error == nil else {
                    logger.debug(response)
                    let result:(success:Bool, message:String, token: String) = (false, "Login Failed", "")
                    return resolve(result)
                }

                if let value = response.result.value {
                    let apiResponseJSONBody = JSON(value)
                    let result:(success:Bool, message:String, token: String) = (true, "", token: apiResponseJSONBody["token"].string!)
                    return resolve(result)
                }
        }
    }
}

来源:https://stackoverflow.com/questions/39092754/swift-alamofire-promise-catching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!