3

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)
                }
        }
    }
}
Cmag
  • 14,946
  • 25
  • 89
  • 140
  • Interesting thing to note, it does not seem that I have to use `dispatch_async`, do I? – Cmag Aug 25 '16 at 04:02
  • is it true that we do not need to call dispatch_async for calling Login(email, password: password).then(onSuccess).catch(onFailure) method? – AppleBee Aug 24 '19 at 14:25

0 Answers0