AFN Simple Package Extraction tool class

Source: Internet
Author: User

? AFN Get Data----by Hanfeng

AFN is the encapsulation of the nsurlconnection,nsurlsession.

AFNetworking3.0 removed the package contents of Nsurlconnection

This is because nsurlsession can completely replace nsurlconnection and has many advantages.

    • Support for network tasks running in the background
    • Pause, stop, and restart network tasks without having to package them yourself nsoperation
    • Support for the continuation of the breakpoint, asynchronous download
    • Support Upload, asynchronous upload
    • Get the download and upload progress

Nsurlsession has 3 kinds of missions.

    1. Nsurlsessiondatatask for small data tasks, such as Web pages
    2. Nsurlsessionuploadtask for uploading
    3. Nsurlsessiondownloadtask for large file downloads

AFNETWORKING3.0 is the encapsulation of the above 3 kinds of tasks, the default support for JSON serialization and deserialization, encapsulating the reachability interpretation network is connected, with excellent error handling mechanism and so on.

When using AFN directly, it is very simple, just need to create an instance object or a single column, then GET or post.

? AFN Package----by Hanfeng

The advantage of isolating the AFN code from the network request code in the project by encapsulating the AFN class is that it is simpler and more convenient to have a major bug in the AFN or to replace the other third-party network request framework. You can imagine how cumbersome it would be to modify and maintain code if our own projects were flooded with AFN network requests directly.

Package AFN only takes 3 steps:

1, create a new class, inherit from AFN, if we only use HTTP, can inherit directly Afhttpsessionmanager

2, a class method is provided in the class for creating objects of this class that can be used in singleton mode

3, an object method is provided in the class for making network requests, providing parameters, and making requests such as GET, POST, head, etc.

Specific Example Demo

1 //2 //ASNetworkingTools.h3 //Test 03-AFN Package OC4 //5 //Created by Hanfeng on 16/4/19.6 //copyright©2016 year Hanfeng. All rights reserved.7 //8 9 #import "AFHTTPSessionManager.h"Ten  One //enumeration that lists the way the request is, and you can continue to add Atypedefenum: nsinteger{ - GET, - POST, the HEADER - }asrequestmethod; -  -  + @interfaceAsnetworkingtools:afhttpsessionmanager -  ++(instancetype) sharedtools; A- (voidRequest: (Asrequestmethod) method urlstring: (NSString *) urlstring parameters: (ID) Parameters Finished: (void(^) (IDresult, Nserror *error)) Finished; at  - @end
////ASNETWORKINGTOOLS.M//Test 03-AFN Package OC////Created by Hanfeng on 16/4/19.//copyright©2016 year Hanfeng. All rights reserved.//#import "ASNetworkingTools.h"@protocolAsnetworkingtoolsproxy <NSObject>/*This method is actually AFN in the Get,post call method-datataskwithhttpmethod However, Xcode does not prompt, you can design a protocol to prompt this method, and make the compilation through this method, you can go to AFN code directly copied over */@optional-(Nsurlsessiondatatask *) Datataskwithhttpmethod: (NSString *) method URLString: (NSString*) urlstring parameters: (ID) Parameters success: (void(^) (Nsurlsessiondatatask *,ID)) Success failure: (void(^) (Nsurlsessiondatatask *, Nserror *)) failure;@end@interfaceAsnetworkingtools () <ASNetworkingToolsProxy>@end@implementationAsnetworkingtools//class methods for Network Tools, Singleton mode+(instancetype) sharedtools{StaticAsnetworkingtools *Sharedtools; Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{Nsurl*baseurl = [Nsurl urlwithstring:@"http://httpbin.org/"]; Sharedtools=[[Self alloc] initwithbaseurl:baseurl];    }); returnSharedtools;}//encapsulates the object method, encapsulates the AFN method into its own-request (parameter 1, parameter 2, parameter 3, Parameter 4) method used in the project-(voidRequest: (Asrequestmethod) method urlstring: (NSString *) urlstring parameters: (ID) Parameters Finished: (void(^) (ID, Nserror *)) finished{NSString*methodname = (method = = GET)?@"GET":@"POST"; /*this encapsulates success and failure, success and failure into a finished method*/[[Self datataskwithhttpmethod:methodname urlstring:urlstring parameters:parameters success:^ (Nsurlsessiondatatask *task,IDresult)    {Finished (result, nil); } Failure:^ (Nsurlsessiondatatask *task, Nserror *error)    {Finished (nil, error);            }] [resume]; if(Method = =GET) {[Self get:urlstring parameters:parameters success:^ (Nsurlsessiondatatask * _nonnull task,ID_nonnull Responseobject)                    {Finished (responseobject, nil); } Failure:^ (Nsurlsessiondatatask * _nonnull task, Nserror *_nonnull Error)                    {Finished (nil, error);            }]; } Else if(Method = =POST) {[Self post:urlstring parameters:parameters success:^ (Nsurlsessiondatatask * _nonnull task,ID_nonnull Responseobject)                    {Finished (responseobject, nil); } Failure:^ (Nsurlsessiondatatask * _nonnull task, Nserror *_nonnull Error)                    {Finished (nil, error);            }]; } Else if(Method = =HEADER) {                //can also be called by enumeration, the HEADER PUT Delete method    }}@end

? Parsing of JSON data----by Hanfeng

JSON data is parsed in a variety of ways,

    1. Apple's native nsjsonserialization
    2. Jsonkit
    3. Sbjson
    4. JSON data returned in AFN mode is automatically parsed

In general, the need for JSON data parsing can be met with an Apple native nsjsonserialization

    • Nsdictionary *json = [nsjsonserialization jsonobjectwithdata:data options:0 error:null];
    • The object returned by JSON parsing is an array or dictionary, depending on whether the original data is enclosed by [] or {}
    • If there is Chinese in the JSON data, the output is Unicode encoded content
    • Nsarray,nsdictionary overriding the-descriptionwithlocale () method
    • NSObject overriding the-description () method

AFN Simple Package Extraction tool class

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.