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
- Get frame
# 更新框架 $ git pull
- View official documents
- Running the demo program
- Building a Learning Branch
分支
is to learn the third-party framework and start the company project an important means!
- Writing a test program
- 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 formatmgr.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 supported
GIF
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
@interface AFAppDotNetAPIClient : AFHTTPSessionManager+ (instancetype)sharedClient;@end
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
AppDelegate
set the cache in
AppDelegate
set the network access indicator in
- Inherit
AFHTTPSessionManager
create single case unified management network access
- 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
URL
Parameters 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