Afnetworking Self-summary

Source: Internet
Author: User
Tags xml parser

afnetworking Introduction
    • Currently the most used third-party framework in domestic development network applications
    • is a Mac OS iOS set of network framework designed for &
    • Yes, NSURLConnection and NSURLSession did the encapsulation.
    • Provides a rich API
    • Provides a perfect solution for errors
    • Easy to use
Official address

Https://github.com/AFNetworking/AFNetworking

Steps to learn a third-party framework
    1. Get frame
      # 更新框架 $ git pull
    2. View official documents
    3. Running the demo program
    4. Building a Learning Branch
      • 分支is to learn the third-party framework and start the company project an important means!
    5. Writing a test program
    6. Less Baidu, if really difficult, can Google
Data format for data format requests
    • Afurlrequestserialization
type Description
AFHTTPRequestSerializer Binary, default
AFJSONRequestSerializer The JSON (POST JSON) RESTful design style requires
AFPropertyListRequestSerializer PList (almost unused in POST plist-development)
Response Data Format
    • AFURLResponseSerialization
type Description
AFHTTPResponseSerializer HTTP binary
AFJSONResponseSerializer The JSON default
AFXMLParserResponseSerializer XML Parser Parser SAX parsing
AFXMLDocumentResponseSerializer (Mac OS X) XML DOM
AFPropertyListResponseSerializer PList almost no
AFImageResponseSerializer Image, GIF not supported
AFCompoundResponseSerializer Combination of
Summary of data formats
    • In most cases, JSON is not required to specify
    • XML format

      • If SAX parsing, you need to specify a format
        mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
      • Then the proxy method is used to resolve

      • If DOM parsing, you need to specify the format

        mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
      • Then use the third-party framework to parse
    • Image

      • AFN support image caching, there are corresponding classification methods and SDWebImage very similar!
      • However: not supportedGIF
Tips
    • When using AFN, be sure to remember the output:error
    • If state code == 200 the data format is wrong, set it for the specific format
Add

The following connections are common XML data formats in mobile development

Http://flash.weather.com.cn/wmaps/xml/china.xml

Official demo program Appdelegate set cache
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];[NSURLCache setSharedURLCache:URLCache];
Set up network access indicators
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
AFAppDotNetAPIClient
    • Provides a global network access portal

    • . h

@interface AFAppDotNetAPIClient : AFHTTPSessionManager+ (instancetype)sharedClient;@end
    • . m
StaticNSString *Const afappdotnetapibaseurlstring = @ "https://api.app.net/";  @implementation afappdotnetapiclient+ (instancetype) sharedclient { static afappdotnetapiclient *_ Sharedclient = Nil; static dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{_sharedclient = [[Afappdotnetapiclient alloc] initwithbaseurl:[NSURL Urlwithstring:afappdotnetapibaseurlstring]]; _sharedclient. securitypolicy = [Afsecuritypolicy policywithpinningmode:afsslpinningmodenone];}); return _sharedclient;} @end            
Summary
    1. AppDelegateset the cache in
    2. AppDelegateset the network access indicator in
    3. Inherit AFHTTPSessionManager create single case unified management network access
    4. A singleton method BaseURL is used, set, and then access the server, you can directly use the relative path
Code Walkthrough General Code Walkthrough
- (void) Postlogin {Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];Nsdictionary *params = @{@ "username":@ "Zhang San & John Doe",@ "Password":@ "123"}; [Mgr POST:@ "http://localhost/login.php" Parameters:params success:^ (afhttprequestoperation *operation,ID responseobject) {NSLog (@ "POST Login%@", responseobject); } failure:^ (Afhttprequestoperation *operation,Nserror *error) {NSLog (@ "%@", error); }];} - (void) GetLogin2 {Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager];Nsdictionary *params = @{@ "username":@ "Zhang San & John Doe",@ "Password":@ "123"}; [Mgr GET:@ "http://localhost/login.php" Parameters:params success:^ (afhttprequestoperation *operation,ID responseobject) {NSLog (@ "GET Login%@", responseobject); } failure:^ (Afhttprequestoperation *operation,Nserror *error) {NSLog (@ "%@", error); }];} - (void) GetLogin1 {Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager]; [Mgr GET:@ "http://localhost/login.php?username=zhangsan&password=123" Parameters:Nil success:^ (Afhttprequestoperation *operation,ID responseobject) {NSLog (@ "%@", responseobject); } failure:^ (Afhttprequestoperation *operation, nserror *error) { nslog (@ "%@", error);}];} -(void) getdemo {Afhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager Manager]; [Mgr Get:@ "Http://localhost/demo.json" Parameters:nil success:^ (afhttprequestoperation *operation, id responseobject) { nslog (@ "%@%@%@", Responseobject, [Responseobject class], [ Span class= "hljs-built_in" >nsthread CurrentThread]); } failure:^ (Afhttprequestoperation *operation, nserror *error) { nslog (@ "%@", error);}];}       
Walkthrough Summary
    • Programmers don't need to know URL , use URL strings directly
    • Automatic JSON deserialization of the implementation
    • Network access completion callback is in the main thread, programmers do not need to consider inter-thread communication
    • URLParameters can be formatted using the ' Dictionary 的形式拼接,程序员不在需要考虑 URL '
    • Programmers do not need to consider percent escapes
      • The percent-semicolon escape in OC is defective, and special characters such as &+= with OC's percent escape are not good, and this time it is necessary to use the method provided in AFN
    • Programmers don't need to know HTTP the method, just pick the word!
XML Parsing sax Parsing
tools.responseSerializer = [AFXMLParserResponseSerializer serializer];
DOM parsing
tools.responseSerializer =[AFHTTPResponseSerializer serializer];
Multi-valued parameters
NetworkTools *tools = [NetworkTools sharedNetworkTools];NSDictionary *params = @{@"city": @[@"bj", @"sh", @"gz"]};[tools GET:@"weather.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"%@", responseObject);} failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"%@", error);}];
PUT Upload & Progress follow up
- (void) Putupload {networktools *tools = [Networktools sharednetworktools];NSString *urlstring =@ "Http://localhost/uploads/321.png";Nsurl *url = [Nsurl Urlwithstring:urlstring]; Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Request. HttpMethod =@ "PUT";Nsurl *fileurl = [[NSBundle Mainbundle] Urlforresource:@ "001.png" withextension:NIL]; Nsprogress *progress =Nil [Tools Uploadtaskwithrequest:request Fromfile:fileurl progress:&progress completionhandler:^ (NSURLResponse * ResponseID Responseobject,Nserror *error) {NSLog (@ "%@%@", response, Responseobject); }] [resume];//KVO [progress addobserver: Selfforkeypath:@ "Completedunitcount" options:nskeyvalueobservingoptionnew Context:nil];} -(void) Observevalueforkeypath: (nsstring *) keypath ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context { if ([Object Iskindofclass:[nsprogress class]]) {nsprogress *progress = object; C10>nslog (@ "%@-%@-%f", Progress. Localizeddescription, Progress. Localizedadditionaldescription, Progress. fractioncompleted); }}
Network Connection Status Monitoring
[Tools. Reachabilitymanager setreachabilitystatuschangeblock:^ (afnetworkreachabilitystatus status) {NSLog (@ "%zd", status); switch (status) {case Afnetworkreachabilitystatusnotreachab Le: nslog (@ "Not Connected"); break; case Afnetworkreachabilitystatusreachableviawifi: NSLog ( Span class= "hljs-string" >@ "Wi-Fi"); break; case Afnetworkreachabilitystatusreachableviawwan: NSLog ( Span class= "hljs-string" >@ "3G"); break; default: nslog (@ "Unknown"); break; }}]; [Tools.reachabilitymanager startmonitoring];        

Afnetworking Self-summary

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.