How to use block / close in quick

In one of my applications, I used a block to call a web service and get a response. Now I want to write this application quickly, but I'm having problems using blocks / closures in Swift. Here is my objective C code that I want to port to swift:

calling a method of the Communicator class

[[Communicator sharedInstance]callWebService:WS_LOGIN withMethod:POST_METHOD andParams:params showLoader:YES completionBlockSuccess:^(id obj) { //Do play with data }completionBlockFailiure:^(id obj) { //Show alert with error }]; 

in class communicator

 -(void)callWebService:(NSString *)serviceName withMethod:(NSString *)methodName andParams:(NSDictionary *)params showLoader:(BOOL)showLoader completionBlockSuccess:(void (^)(id))aBlock completionBlockFailiure:(void (^)(id))aFailBlock { if (showLoader) { // show loader } [self performRequestWithServiceName:serviceName method:methodName andParams:params successblock:aBlock failureblock:aFailBlock]; } - (void)performRequestWithServiceName:(NSString *)serviceName method:(NSString*)methodName andParams:(NSDictionary*)params successblock:(void (^)(id obj))successBlock failureblock:(void (^)(id obj))failBlock { if(callSuceess){ successBlock(@"Success"); }else{ successBlock(nil); } } 
+5
source share
5 answers

For Swift. Use AnyObject for id objc type.

 func callWebservice (serviceName: String, withMethod method: String, andParams params: NSDictionary, showLoader loader: Bool, completionBlockSuccess aBlock: ((AnyObject) -> Void), andFailureBlock failBlock: ((AnyObject) -> Void)) { if loader { // Show loader } performRequestWithServiceName(serviceName, method: method, andParams: params, success: aBlock, failure: failBlock) } func performRequestWithServiceName(serviceName: String, method methodName: String, andParams params: NSDictionary, success successBlock: ((AnyObject) -> Void), failure failureBlock: ((AnyObject) -> Void)) { if callSuceess { successBlock("Success") }else { successBlock(nil) } } 

UPDATE: an example when you want to call web service . See code below

 callWebservice("your-service-name", withMethod: "your-method", andParams: ["your-dic-key": "your dict value"], showLoader: true/*or false*/, completionBlockSuccess: { (success) -> Void in // your successful handle }) { (failure) -> Void in // your failure handle } 
+3
source

Your code might look like this:

 func callWebService(serviceName: String, method: String, params: [String : AnyObject], showLoader: Bool, success: (responseObject: AnyObject) -> Void, failure: (responseObject: AnyObject) -> Void) { if showLoader { // show loader } performRequest(serviceName, method: method, params: params, success: success, failure: failure) } func performRequest(serviceName: String, method: String, params: [String : AnyObject], success: (responseObject: AnyObject) -> Void, failure: (responseObject: AnyObject) -> Void) { } 

I replaced NSDictionary with [String : AnyObject] . If you can replace any use of AnyObject more specific types, your code will be cleaner and more stable.

+2
source

For Swift Closures we should use ( ) -> ( )

For instance:

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

You can call it like:

 yourFunction({(response) -> Void in // Success }) { (error) -> Void in // Handle Errors } 

We hope this helps you create Closures with your requirements.

+1
source

In the communicator class, the method that the web service computes will be defined like this, depending on the type of object you want to return

 func performRequest(serviceName: NSString, methodName: NSString,paramaters:NSDictionary, successblock: (String)->(), failureBlock: () -> ()) { if(callSuccess) { successblock("Success") } else { failureBlock() } 

We determine the types of success and failure blocks, since their function signatures in the above case are defined as a method that takes a string as an input parameter and returns nothing, so we can then call successBlock, passing in a string. The failure block is defined above as a block that takes no parameters and returns nothing.

To call this method

 func callWebService(serviceName: NSString, method: NSString and parameters: NSDictionary, showLoader: Bool, completionBlockSuccess:(String) -> (), completionBlockFailiure:() -> ()) { if (showLoader) { // show loader } performRequest(serviceName: serviceName, methodName: method, parameters, successBlock:completionBlockSuccess, failureBlock: completionBlockFailiure) } 

Finally, to call it

 Communicator.sharedInstance().callWebService(serviceName: WS_LOGIN , method: POST_METHOD and parameters: params, showLoader: true, completionBlockSuccess:{ returnedString in //Do play with data }, completionBlockFailiure:{ //Show alert with error }) 

In the completion block, we define the variable returnString so that we can manipulate this input parameter (in the example above, this will be the string "Success"). I assume that your data does not just return a string, although you may have to play around with it, depending on what your service returns.

Also here I tried to match your method signatures using NSString and NSDictionary, although depending on your needs, more suitable equivalents to String and [String: AnyObject] may be more appropriate.

+1
source
 func processingWithAnyObject(input: String, completion: @escaping (_ result: AnyObject) -> Void) { ... completion(response.result.value! as AnyObject) } processingWithAnyObject("inputString") { (result: AnyObject) in print("back to caller: \(result)") } 
0
source

All Articles