7

How would I write this block function in swift. I've read through on the subject but the syntax just doesn't make much sense to me.

MyAppRequest *request = [_agent login];
    [request sendWithLoadMessage:@"Signing In"
    successMessage:@"Signed In"
    failureMessage:@"Failed to log in"
    recoveryOptions:@"If you keep having trouble, try going to http://mystrou.firehosehelp.com and try loggin in there. If that fails, try resetting your password"
    success:^(MyAppResponse *response) {
        PREFS.authToken = _agent.accessToken;
        [_delegate loginViewController:self loggedInAgent:_agent];
    } failure:^(MyAppResponse *response) {

    }];
1
  • 1
    Please post more code - there are parts of the call missing. Commented Oct 1, 2014 at 4:39

2 Answers 2

19

It's not that hard actually. called closures in Swift).

public func someFunction(success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void) {

}

And here's how you call it.

someFunction(success: { (response) -> Void in
    // Handle success response
}) { (error?) -> Void in
    // Do error handling stuff
}

In your case, I'm getting this block handles some server response. Most probably logging in. The success block would be called if the network operation succeeds. Inside it, you save the received access token from your server.

The failure block is called if the network request fails. You might want to log the error out, display an alert to the user stuff like that in it.

If you're confused about the syntax I suggest refer to these two sites. For Objective-C block syntax and for Swift closure syntax.

Sign up to request clarification or add additional context in comments.

Comments

0

thanks to @isuru I figured this out:

let request: MyAppRequest = agent .login()

request .sendWithLoadMessage("Signing in",
        successMessage: "Signed in",
        failureMessage: "Failed to login",
        recoveryOptions: "Figuring it out",
        success: { (response: MyAppResponse!) -> Void in MyAppSettings().authenticatingToken = agent.accessToken
        }) { (response: MyAppResponse!) -> Void in
            var alert = UIAlertController(title: "Oops!", message: "You haven't figured out the token thing!", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.