Open-source Chinese IOS client learning-(8) Network Communication afnetworking class library

Source: Internet
Author: User

Afnetworking is a lightweight IOS network communication library. After the ASI class library is not updated, developers have a set of good choices;

Afnetworking Library source code download and use tutorial: https://github.com/AFNetworking/AFNetworking

If you want to study in depth there is an official document Introduction: http://afnetworking.github.com/AFNetworking/

In the open-source Chinese IOS client, only two instance methods are used for the afnetworking class library.

(1) getpath: parameters: Success: Failure:

(2) postpath: parameters: Success: Failure:

Their usage is basically the same, but the data request methods are different. One is GET request and POST request. Get is a type of request to request data from the server. It is equivalent to querying information and does not modify the class capacity. Post is a type of request to submit data to the server, which affects the data content; two methods are defined:

- (void)getPath:(NSString *)path      parameters:(NSDictionary *)parameters         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];    [self enqueueHTTPRequestOperation:operation];}

- (void)postPath:(NSString *)path       parameters:(NSDictionary *)parameters          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];    [self enqueueHTTPRequestOperation:operation];}

Getpath: parameters: Success: Failure: example of how to use the method in a program:

Newsview. m

-(Void) Reload :( bool) norefresh {// if there is a network connection if ([config instance]. isnetworkrunning) {If (isloading | isloadover) {return;} If (! Norefresh) {allcount = 0;} int pageindex = allcount/20; nsstring * URL; Switch (self. Catalog) {Case 1: url = [nsstring stringwithformat: @ "% @? Catalog = % d & pageindex = % d & pagesize = % d ", api_news_list, 1, pageindex, 20]; break; Case 2: url = [nsstring stringwithformat: @ "% @? Type = Latest & pageindex = % d & pagesize = % d ", api_blog_list, pageindex, 20]; break; Case 3: url = [nsstring stringwithformat: @" % @? Type = recommend & pageindex = % d & pagesize = % d ", api_blog_list, pageindex, 20]; break;} [[afoscclient sharedclient] getpath: URL parameters: Nil success: ^ (afhttprequestoperation * operation, Id responseobject) {[Tool getoscnotice2: operation. responsestring]; isloading = no; If (! Norefresh) {[self clear];} @ try {nsmutablearray * newnews = self. Catalog <= 1? [Tool readstrnewsarray: operation. responsestring andold: News]: [Tool readstruserblogsarray: operation. responsestring andold: News]; int COUNT = [Tool islistover2: operation. responsestring]; allcount + = count; If (count <20) {isloadover = yes;} [News addobjectsfromarray: newnews]; [self. tablenews reloaddata]; [self doneloadingtableviewdata]; // if it is the first page, it is cached if (News. count <= 20) {[Tool savecache: 5 andid: Self. catalog andstring: operation. responsestring] ;}@ catch (nsexception * exception) {[takeexception: exception] ;}@ finally {[self doneloadingtableviewdata] ;}} failure: ^ (afhttprequestoperation * operation, nserror * error) {nslog (@ "An error occurred while retrieving the news List"); // if it is refreshing [self doneloadingtableviewdata]; If ([config instance]. isnetworkrunning = No) {return;} isloading = no; If ([config instance]. isnetworkrunning) {[Tool toastnotification: @ "error network not connected" andview: Self. view andloading: No andisbottom: No] ;}}]; isloading = yes; [self. tablenews reloaddata];} // if no network connection exists, else {nsstring * value = [Tool getcache: 5 andid: Self. catalog]; If (value) {nsmutablearray * newnews = [Tool readstrnewsarray: Value andold: News]; [self. tablenews reloaddata]; isloadover = yes; [News addobjectsfromarray: newnews]; [self. tablenews reloaddata]; [self doneloadingtableviewdata] ;}}

Analyze the code below:

The first is to make a network connection judgment. This article describes how to learn from the open-source Chinese IOS client-(6) network connection detection. The author does not use this method to determine, but uses getpath: parameters: Success: Failure: used to determine the network connection. afhttprequestoperation and "patch" are used to request the HTTP client to operate the queue, and block blocks (IOS
4.0 + features). The URL request is successfully executed in the success block, where the block does not return values. Two parameters are accepted, and the request operation and response data request are created, the method in failure failed to be executed in the URL request. There is no returned value in this block. Two parameters are accepted to create the request and the nserror object to describe the network or resolution error;

In[Config instance] In if (). isnetworkrunning = Yes. If the program is loaded or loaded, nothing is returned. If the program does not load data, the number of data lists is displayed as 0. Next, in switch, set different api interfaces () based on the user's choice, and parse and display the data information in the view;


In the afnetwork folder, the author adds an afoscclient class that inherits afhttpclient and designs a sharedclient class method, from the returned results, it can be inferred that it returns JSON-type data through API requests, but the specific function has not yet been seen;

[Tool getoscnotice2: operation. responsestring]; is an XML file encapsulated in the parsing obtained in the tool class.


If the URL request is successful, an exception is processed to prevent the program from crashing abnormally when the request data is successful.

Usage of @ try @ catch @ finally exception handling:


@ Try
{
// Executed code, which may be abnormal. Once an exception is found, the system immediately jumps to catch for execution. Otherwise, the content in the catch will not be executed.
}
@ Catch
{
// The code here will not be executed unless an exception occurs during code execution in try.
}
@ Finally
{
// Execute whatever the situation, including using return in try catch. It can be understood that as long as a try or catch is executed, finally will be executed.
}

If an error occurs in the data requested by the URL, the network is not connected and the data cannot be loaded. The gcdiscreeticationicationview prompt is displayed, indicating a network error;

Postpath: parameters: Success: Failure:Example:

Friendsview. m

-(Void) Reload :( bool) norefresh {If (isloadover) {[self doneloadingtableviewdata]; return;} [[afoscclient sharedclient] postpath: api_friends_list parameters: [nsdictionary attributes: segement. selectedsegmentindex = 0? @ "1": @ "0", @ "relation", [nsstring stringwithformat: @ "% d", friends. count/20], @ "pageindex", @ "20", @ "pagesize", [nsstring stringwithformat: @ "% d", [config instance]. getuid], @ "uid", nil] success: ^ (afhttprequestoperation * operation, Id responseobject) {If (! Norefresh) {[self clear];} [self doneloadingtableviewdata]; isloading = no; nsstring * response = operation. responsestring; [Tool getoscnotice2: Response]; @ try {tbxml * xml = [[tbxml alloc] initwithxmlstring: response error: Nil]; tbxmlelement * root = xml. rootxmlelement; // display tbxmlelement * _ friends = [tbxml childelementnamed: @ "friends" parentelement: Root]; If (! _ Friends) {isloadover = yes; [self. tablefriends reloaddata]; return;} tbxmlelement * First = [tbxml childelementnamed: @ "friend" parentelement: _ friends]; If (first = nil) {[self. tablefriends reloaddata]; isloadover = yes; return;} nsmutablearray * newfriends = [[nsmutablearray alloc] limit: 20]; tbxmlelement * name = [tbxml childelementnamed: @ "name" parentelement: first]; tbxmlelement * us Erid = [tbxml childelementnamed: @ "userid" parentelement: First]; tbxmlelement * portrait = [tbxml childelementnamed: @ "portrait" parentelement: First]; tbxmlelement * expertise = [tbxml response: @ "expertise" parentelement: First]; tbxmlelement * Gender = [tbxml childelementnamed: @ "gender" parentelement: First]; friend * f = [[friend alloc] initwithparameters: [tbxml textforelement: Name] anduid: [[TB XML textforelement: userid] intvalue] andportrait: [tbxml textforelement: Portrait] andexpertise: [tbxml textforelement: expertise] andmale: [[tbxml textforelement: Gender] intvalue] = 1]; if (! [Tool isrepeatfriend: Friends andfriend: f]) {[newfriends addobject: F];} while (first) {First = [tbxml nextsiblingnamed: @ "friend" searchfromelement: First]; if (first) {name = [tbxml childelementnamed: @ "name" parentelement: First]; userid = [tbxml childelementnamed: @ "userid" parentelement: First]; portrait = [tbxml childelementnamed: @ "portrait" parentelement: First]; expertise = [tbxml childelementn Amed: @ "expertise" parentelement: First]; Gender = [tbxml childelementnamed: @ "gender" parentelement: First]; F = [[friend alloc] initwithparameters: [tbxml textforelement: name] anduid: [[tbxml textforelement: userid] intvalue] andportrait: [tbxml textforelement: Portrait] andexpertise: [tbxml textforelement: expertise] andmale: [tbxml textforelement: gender] intvalue] = 1]; If (! [Tool isrepeatfriend: Friends andfriend: f]) {[newfriends addobject: F] ;}} else break;} If (newfriends. count <20) {isloadover = yes;} [friends addobjectsfromarray: newfriends]; [self. tablefriends reloaddata];} @ catch (nsexception * exception) {[Your takeexception: exception];} @ finally {[self doneloadingtableviewdata];} failure: ^ (afhttprequestoperation * operation, nserror * error) {nslog (@ "friends list retrieval error"); [self doneloadingtableviewdata]; isloading = no; If ([config instance]. isnetworkrunning) {[Tool toastnotification: @ "error network not connected" andview: Self. view andloading: No andisbottom: No] ;}}]; isloading = yes; [self. tablefriends reloaddata];}

This method is different from getpath: parameters: Success: failure: the request method is post, and data can be submitted to the server;

Related Article

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.