AFNetworking
AFNetworking是一个轻量级的iOS网络通信类库。它建立在NSURLConnection之上
注:AFNetworking 依赖包:UIKit , SystemConfiguration,MobileCoreServices,Security ;AFNetworking 2.5版本以后,需要Xcode 6.3以上才支持
默认提交请求的数据是二进制的,返回格式是JSON如果提交数据是JSON的,需要将请求格式设置为AFJSONRequestSerializer
请求格式:
AFHTTPRequestSerializer 二进制格式
AFJSONRequestSerializer JSON
AFPropertyListRequestSerializer PList(是一种特殊的XML,解析起来相对容易)
返回格式:
AFHTTPResponseSerializer 二进制格式
AFJSONResponseSerializer JSON
AFXMLParserResponseSerializer XML,只能返回XMLParser,还需要自己通过代理方法解析
AFXMLDocumentResponseSerializer (Mac OS X)
AFPropertyListResponseSerializer PList
AFImageResponseSerializer Image
AFCompoundResponseSerializer 组合
// 设置请求格式
manager.requestSerializer= [AFJSONRequestSerializerserializer];
// 设置返回格式
manager.responseSerializer= [AFHTTPResponseSerializerserializer];
GETRequest
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];
[managerGET:@"http://example.com/resources.json"parameters:nilsuccess:^(AFHTTPRequestOperation *operation,idresponseObject) {NSLog(@"JSON:%@", responseObject);}failure:^(AFHTTPRequestOperation *operation,NSError*error) {NSLog(@"Error:%@", error);}];
POSTURL-Form-Encoded Request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];NSDictionary*parameters = @{@"foo":@"bar"};[managerPOST:@"http://example.com/resources.json"parameters:parameterssuccess:^(AFHTTPRequestOperation *operation,idresponseObject) {NSLog(@"JSON:%@", responseObject);}failure:^(AFHTTPRequestOperation *operation,NSError*error) {NSLog(@"Error:%@", error);}];
POSTMulti-Part Request —— 多文件上传,建议用AFURLSessionManager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];AFURLSessionManagerNSDictionary*parameters = @{@"foo":@"bar"};NSURL*filePath = [NSURLfileURLWithPath:@"file://path/to/image.png"]; [managerPOST:@"http://example.com/resources.json"parameters:parametersconstructingBodyWithBlock:^(id formData) { [formDataappendPartWithFileURL:filePathname:@"image"error:nil]; }success:^(AFHTTPRequestOperation *operation,idresponseObject) {NSLog(@"Success:%@", responseObject); }failure:^(AFHTTPRequestOperation *operation,NSError*error) {NSLog(@"Error:%@", error); }];
Creating an Upload Task —— 上传磁盘上的文件,使用uploadTaskWithRequest方式,需要指定fromFile的位置(这种方式从磁盘加载,降低内存的使用),request中不封装上传文件
AFURLSessionManager*manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
NSURL*url = [NSURLURLWithString:@"http://www.freeimagehosting.net/upload.php"];
//创建request,设置属性
NSMutableURLRequest* request = [NSMutableURLRequestrequestWithURL:url];
// application/json
[requestaddValue:@"image/png”forHTTPHeaderField:@"Content-Type"];
[requestaddValue:@"application/json”forHTTPHeaderField:@"Accept"];
[requestsetHTTPMethod:@"POST"];
[requestsetCachePolicy:NSURLRequestReloadIgnoringCacheData];
[requestsetTimeoutInterval:60];
NSProgress*progress =nil;//上传进度
//创建本地文件路径,这里不从内存取数据,直接读取磁盘,减少内存使用
NSString*path = [[NSBundlemainBundle]pathForResource:@"qqq"ofType:@"png"];
NSURL* local_url = [NSURLfileURLWithPath:path];
NSURLSessionUploadTask*uploadTask = [manageruploadTaskWithRequest:requestfromFile:local_urlprogress:&progresscompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error) {
if(error) {
NSLog(@"Error: %@", error);
}else{
NSLog(@"%@ %@", response, responseObject);
}
}];
//对进度添加监听,并实时更新进度条
[progressaddObserver:selfforKeyPath:@“fractionCompleted"options:NSKeyValueObservingOptionNewcontext:NULL];
//开启任务
[uploadTaskresume];
//监测上传进度
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
if([keyPathisEqualToString:@"fractionCompleted"] && [objectisKindOfClass:[NSProgressclass]]) {
NSProgress*progress = (NSProgress*)object;
NSLog(@"[MainVC] Uploading photo fraction = %f, completed unit count = %lld, total unit count = %lld", progress.fractionCompleted, progress.completedUnitCount, progress.totalUnitCount);
dispatch_async(dispatch_get_main_queue(), ^{
// self.imageUploadProgress.progress = progress.fractionCompleted;
});
}
}
Creating an Upload Task —— Stream方式上传文件,速度和uploadTaskWithRequest差不多,request里需要封装formData
//在request里封装formData信息;
NSMutableURLRequest*request = [[AFHTTPRequestSerializerserializer]multipartFormRequestWithMethod:@"POST"URLString:@"http://www.freeimagehosting.net/upload.php"parameters:nilconstructingBodyWithBlock:^(id formData) {
UIImage*img = [UIImageimageNamed:@"qqq"];
NSData*imageData =UIImagePNGRepresentation(img);
//一定要指定mimeType
//appendPartWithFileData:从内存中加载附件,也可以用appendPartWithFileURL:从磁盘加载附件
[formDataappendPartWithFileData:imageDataname:@"file"fileName:@"qqq.jpg"mimeType:@"image/png"];
}error:nil];
//进度
NSProgress*progress =nil;
AFURLSessionManager*manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
NSURLSessionUploadTask*uploadTask = [manageruploadTaskWithStreamedRequest:requestprogress:&progresscompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error) {
if(error) {
NSLog(@"Error: %@", error);
}else{
NSLog(@"%@ %@", response, responseObject);
}
}];
//监听上传进度
[progressaddObserver:selfforKeyPath:@"fractionCompleted"options:NSKeyValueObservingOptionNewcontext:NULL];
[uploadTaskresume];
//监测上传进度
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
if([keyPathisEqualToString:@"fractionCompleted"] && [objectisKindOfClass:[NSProgressclass]]) {
NSProgress*progress = (NSProgress*)object;
NSLog(@"[MainVC] Uploading photo fraction = %f, completed unit count = %lld, total unit count = %lld", progress.fractionCompleted, progress.completedUnitCount, progress.totalUnitCount);
dispatch_async(dispatch_get_main_queue(), ^{
// self.imageUploadProgress.progress = progress.fractionCompleted;
});
}
}
Creating a Download Task —— 断点下载
@property(nonatomic,strong)NSURLSessionDownloadTask*downloadTask ;
@property(nonatomic,strong)NSData* data;//存储进度
@property(nonatomic,strong)AFURLSessionManager*manager ;
@property(nonatomic,strong)NSURLRequest*request;
//下载
-(void)download
{
_manager= [[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
_request= [NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://dl1.24money.com/haoying/HY_Setup_zolzol.exe"]];
NSProgress*progress=nil;//存放进度
_downloadTask= [_managerdownloadTaskWithRequest:_requestprogress:&progressdestination:^NSURL*(NSURL*targetPath,NSURLResponse*response) {
//下载后文件存放路径
NSURL*documentsDirectoryURL = [[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];
return[documentsDirectoryURLURLByAppendingPathComponent:[responsesuggestedFilename]];
}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[progressaddObserver:selfforKeyPath:@"fractionCompleted"options:NSKeyValueObservingOptionNewcontext:NULL];
[_downloadTaskresume];
}
//暂停下载
-(void)pause
{
[_downloadTaskcancelByProducingResumeData:^(NSData*resumeData) {
_data=resumeData;//这里resumeData保存下载URL,下载的字节数、等进度信息
}];
_downloadTask=nil;
}
//恢复下载
-(void)resume
{
NSProgress*pro =nil;
_downloadTask=[_managerdownloadTaskWithResumeData:_dataprogress:&prodestination:^NSURL*(NSURL*targetPath,NSURLResponse*response) {
NSURL*documentsDirectoryURL = [[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];
return[documentsDirectoryURLURLByAppendingPathComponent:[responsesuggestedFilename]];
}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error) {
}];
[proaddObserver:selfforKeyPath:@"fractionCompleted"options:NSKeyValueObservingOptionNewcontext:NULL];
[_downloadTaskresume];
}
//监测上传进度
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
if([keyPathisEqualToString:@"fractionCompleted"] && [objectisKindOfClass:[NSProgressclass]]) {
NSProgress*progress = (NSProgress*)object;
NSLog(@"完成百分比:%f,完成字节数:%lld,总共字节数:%lld", progress.fractionCompleted, progress.completedUnitCount, progress.totalUnitCount);
dispatch_async(dispatch_get_main_queue(), ^{
//主线程更新UI
});
}
}
Creating a Data Task —— 下载data任务(音乐、视频、网页等文件)
AFURLSessionManager*manager = [[AFURLSessionManageralloc]initWithSessionConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]];
NSURL*URL = [NSURLURLWithString:@"http://blog.csdn.net/majiakun1/article/details/38133703”];
NSURLRequest*request = [NSURLRequestrequestWithURL:URL];
//设置返回类型为二进制类型,参数必须设置
manager.responseSerializer= [AFHTTPResponseSerializerserializer];
NSURLSessionDataTask*dataTask = [managerdataTaskWithRequest:requestcompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error) {
if(error) {
NSLog(@"Error: %@", error);
}else{
//返回码
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSIntegerresponseStatusCode = [httpResponsestatusCode];
NSLog(@"%ld", responseStatusCode);
//在webview中显示返回结果
[self.webViewloadData:responseObject
MIMEType:@"text/html"
textEncodingName:@"utf-8"
baseURL:nil];
}
}];
[dataTaskresume];
HTTP Manager Reachability(1)
[[AFNetworkReachabilityManagersharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {NSLog(@"Reachability:%@",AFStringFromNetworkReachabilityStatus(status));
switch(status) {caseAFNetworkReachabilityStatusReachableViaWWAN:caseAFNetworkReachabilityStatusReachableViaWiFi: [operationQueuesetSuspended:NO];break;caseAFNetworkReachabilityStatusNotReachable:default: [operationQueuesetSuspended:YES];break; }
}];
[[AFNetworkReachabilityManagersharedManager]startMonitoring];
HTTP Manager Reachability(2)
NSURL*baseURL = [NSURLURLWithString:@"http://example.com/"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManageralloc]initWithBaseURL:baseURL];NSOperationQueue*operationQueue = manager.operationQueue;[manager.reachabilityManagersetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {switch(status) {caseAFNetworkReachabilityStatusReachableViaWWAN:caseAFNetworkReachabilityStatusReachableViaWiFi: [operationQueuesetSuspended:NO];break;caseAFNetworkReachabilityStatusNotReachable:default: [operationQueuesetSuspended:YES];break; }}];[manager.reachabilityManagerstartMonitoring];
网络状态:
AFNetworkReachabilityStatusUnknown = -1, // 未知
AFNetworkReachabilityStatusNotReachable = 0, // 无连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花钱
AFNetworkReachabilityStatusReachableViaWiFi = 2, // 局域网络,不花钱
Allowing Invalid SSL Certificates —— 允许不可用的的SSL证书
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];manager.securityPolicy.allowInvalidCertificates =YES;// not recommended for production