Mac OS
& iOS
設計的一套網絡框架NSURLConnection
和 NSURLSession
作了封裝https://github.com/AFNetworking/AFNetworkingphp
$ git clone https://github.com/AFNetworking/AFNetworking.git
# 更新框架 $ git pull
分支
是學習第三方框架和入手公司項目的重要手段!類型 | 說明 |
---|---|
AFHTTPRequestSerializer |
二進制的,默認的 |
AFJSONRequestSerializer |
JSON(POST JSON) RESTful 設計風格須要 |
AFPropertyListRequestSerializer |
PList(POST Plist-開發中幾乎不用) |
AFURLResponseSerialization
類型 | 說明 |
---|---|
AFHTTPResponseSerializer |
HTTP 二進制的 |
AFJSONResponseSerializer |
JSON 默認的 |
AFXMLParserResponseSerializer |
XML Parser 解析器 SAX 解析 |
AFXMLDocumentResponseSerializer |
(Mac OS X) XML DOM |
AFPropertyListResponseSerializer |
PList 幾乎不用 |
AFImageResponseSerializer |
圖像,不支持 GIF |
AFCompoundResponseSerializer |
組合的 |
XML 格式git
SAX
解析,須要指定格式 mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
而後利用代理方法解析程序員
若是 DOM 解析,須要指定格式github
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
圖像json
SDWebImage
很是像!GIF
error
state code == 200
,就是數據格式錯誤,針對具體格式進行設置便可如下鏈接是移動開發中,常見的 XML 數據格式api
http://flash.weather.com.cn/wmaps/xml/china.xml緩存
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; [NSURLCache setSharedURLCache:URLCache];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
AFAppDotNetAPIClient
提供全局網絡訪問入口bash
.h服務器
@interface AFAppDotNetAPIClient : AFHTTPSessionManager + (instancetype)sharedClient; @end
static NSString * 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
AppDelegate
中設置緩存AppDelegate
中設置網絡訪問指示器AFHTTPSessionManager
建立單例統一管理網絡訪問BaseURL
,設置後,再訪問該服務器,能夠直接使用相對路徑- (void)postLogin { AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; NSDictionary *params = @{@"username": @"張三&李四", @"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": @"張三&李四", @"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], [NSThread currentThread]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }]; }
URL
,直接使用 URL
字符串JSON
的反序列化URL
的參數能夠使用 `字典的形式拼接,程序員不在須要考慮
url` 的格式HTTP
方法,只須要挑選單詞便可!tools.responseSerializer = [AFXMLParserResponseSerializer serializer];
tools.responseSerializer =[AFHTTPResponseSerializer serializer];
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); }];
- (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 *response, id responseObject, NSError *error) { NSLog(@"%@ %@", response, responseObject); }] resume]; // KVO [progress addObserver:self forKeyPath:@"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; NSLog(@"%@ - %@ - %f", progress.localizedDescription, progress.localizedAdditionalDescription, progress.fractionCompleted); } }
[tools.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"%zd", status); switch (status) { case AFNetworkReachabilityStatusNotReachable: NSLog(@"沒有鏈接"); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WI-FI"); break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"3G"); break; default: NSLog(@"未知"); break; } }]; [tools.reachabilityManager startMonitoring];