Writing Block Functions in Swift

How to write this block function in swift. I read this topic, but the syntax just doesn't make any 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) { }]; 
+7
function objective-c swift objective-c-blocks
source share
2 answers

It’s not so difficult actually. called Swift closures).

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

And that's what you call it.

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

In your case, I get this block, processing the server response. Most likely, login. The success block will be called if the network operation completes successfully. In it, you save the received access token from your server.

The failure block is called if the network request fails. You might want to display an error message, display a warning that there is a user in it.

If you are confused by the syntax, I suggest referring to these two sites. For Objective-C block syntax and for Swift close syntax .

+19
source share

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) } 
0
source share

All Articles