Use block to optimize the integrated code in the network request callback Mode

Source: Internet
Author: User

There are often repetitive tasks in the project. If you don't want to go far, you can say HTTP and socket, send a request, and return success or failure. Every time I need to process successful and failed callbacks at different logic levels, the disadvantage is that the Code is scattered and lengthy, and there are a lot of code repetition. So I used block to optimize this problem. This document uses the asihttprequest library to describe this method based on the Basic HTTP request and get method.

Final effect:

1     [[PPDHttpRequest shareInstance] requestWithUrlString:@"http://192.168.2.99:5009/message/init/1032/13/0/1" complection:^(id arg) {2         //3         NSLog(@"%@", arg);4     } failure:^(id arg) {5         //6         NSLog(@"%@", arg);7     }];

The three parameters are get Method URL, successful block "Callback", and failed block "Callback ". Requests and results are integrated into the same function, which is clear and easy to maintain.

Complete demo address: https://github.com/pigpigdaddy/HttpRequestUsingBlockDemo

 

The following describes the key points one by one:

I. Singleton Mode

The Singleton mode is also used to simplify, reduce, and manage data in a unified manner. The usage and Principles of the singleton mode are not discussed in this article. In my opinion, in an app, the "underlying" network interface is like an HTTP interface. It is okay to use a class. All HTTP network requests can be implemented through this class interface. If separate calls are required for functions of different modules, You can encapsulate them and separate different classes to be responsible for HTTP calls of different modules. Now that the underlying layer only needs one class and the entire program may need to process HTTP network requests at any time, I decided to make it into a singleton for processing.

1 @ interface ppdhttprequest: nsobject 2 3/** 4 todo: Get instance Singleton 5 6 @ return urhttprequest Instance Object 7 8 @ author pigpigdaddy 9 @ since10 */11 + (instancetype) wait instance; 12 13 @ end
1/** 2 todo: Get instance Singleton 3 4 @ return urhttprequest Instance Object 5 6 @ author pigpigdaddy 7 @ since 8 */9 + (instancetype) wait instance {10 static ppdhttprequest * httprequest; 11 static login oncetoken; 12 dispatch_once (& oncetoken, ^ {13 httprequest = [[ppdhttprequest alloc] init]; 14}); 15 return httprequest; 16}

The preceding Code creates a singleton in a standard arc environment.

 

2. Add a request interface. The method parameters include successful and failed blocks.

The following method is used to call a method:

1/** 2 todo: HTTP request 3 4 @ Param urlstring request address 5 @ Param parameters request parameter 6 @ Param complection Block 7 @ Param Failure block 8 9 @ author pigpigdaddy10 @ since 3.011 */12 -( void) requestwithurlstring :( nsstring *) urlstring complection :( commonblock) complection failure :( commonblock) failure;
1/** 2 todo: HTTP request 3 4 @ Param urlstring request address 5 @ Param parameters request parameter 6 @ Param complection Block 7 @ Param Failure block 8 9 @ author pigpigdaddy10 @ since 3.011 */12 -( void) requestwithurlstring :( nsstring *) urlstring complection :( commonblock) complection failure :( commonblock) failure13 {14 nslog (@ "--------------- ppdhttprequest URL: % @ -----------", urlstring ); 15 nsurl * url = [nsurl urlwithstring: urlstring]; 16 asihttprequest * request = [[asihttprequest alloc] initwithurl: url]; 17 [asihttprequest failed: 60]; 18 [Request setdelegate: self]; 19 [Request setrequestmethod: @ "get"]; 20 [Request setshouldattemptpersistentconnection: No]; 21 22 // Add information object 23 nsmutabledictionary * userinfo = [nsmutabledictionary dictionary]; 24 if (complection) {25 [userinfo setobject: complection forkey: @ "complectionblock"]; 26} 27 if (failure) {28 [userinfo setobject: Failure forkey: @ "failureblock"]; 29} 30 [Request setuserinfo: userinfo]; 31 32 [self. queue addoperation: request]; 33}

As you can see, in addition to the get Method URL, the interface call also contains two blocks. The types of these two blocks are defined in the following way:

1 // define the general block2 typedef void (^ commonblock) (ID Arg );

Has an ID parameter for "return value ".

In method implementation, I set two blocks to userinfo, so that the corresponding processing can be performed in the HTTP callback.

 

3. Process callback

As stated in article 2, in the HTTP callback, let the corresponding block make the correct response:

 1 - (void)requestFinished:(ASIHTTPRequest *)request{ 2     NSDictionary *userInfo = request.userInfo; 3     commonBlock complection = [userInfo objectForKey:@"complectionBlock"]; 4     if (complection){ 5         complection(request.responseString); 6     } 7 } 8  9 - (void)requestFailed:(ASIHTTPRequest *)request{10     NSDictionary *userInfo = request.userInfo;11     commonBlock failure = [userInfo objectForKey:@"failureBlock"];12     if (failure){13         failure(request.responseString);14     }15 }

The final effect is like the code posted at the beginning of the article, integrating requests and callbacks. The code is concise, clear, and easy to use. It is also easy to encapsulate twice.

For more information, you can use different methods for upper-layer encapsulation, accept various parameters, splice them into URLs (get), or form (post ),And most importantly, the block parameter passed in successfully fails.!

 

Complete demo address: https://github.com/pigpigdaddy/HttpRequestUsingBlockDemo

Reference:

Http://www.cnblogs.com/eagle927183/p/3457538.html

Http://sjpsega.com/blog/2014/05/25/singleton-in-ios/

Http://blog.csdn.net/gideal_wang/article/details/4316691

Use block to optimize the integrated code in the network request callback Mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.