–AFNetworking(AFN)
新建项目并导入 AFN 框架 的步骤
•1. 将框架程序拖拽进项目
•2. 添加iOS框架引用
–SystemConfiguration.framework
–MobileCoreServices.framework
•3. 修改xxx-Prefix.pch文件
#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
AFN——AFHTTPClient
•1. 使用baseURL实例化
•2. 建立NSURLRequest
Ø创建GET、HEAD、PUT、DELETE方法请求
²requestWithMethod:path:parameters:
Ø创建POST方法请求
²multipartFormRequestWithMethod:path:parameters:
constructingBodyWithBlock:
•3. 检测网路连接状态
–setReachabilityStatusChangeBlock
AFHttpRequestOperation —— 对 NSURLConnection 的封装
•AFHttpRequestOperation HTTP请求操作
ØAFJSONRequestOperation 对JSON请求的封装
ØAFXMLRequestOperation 对XML请求的封装
ØAFPropertyListRequestOperation 对Plist请求的封装
ØAFImageRequestOperation 对图像请求的封装
Ø
•块代码操作
ØsetCompletionBlockWithSuccess 设置请求完成块代码
ØsetUploadProgressBlock 设置上传进度块代码
ØsetDownloadProgressBlock 设置下载进度块代码
•下载操作需要设置outputStream
Ø针对请求的操作pause(暂停)resume(继续)
// 关于暂停和继续,AFN中的数据不是线程安全的
// 如果使用操作的暂停和继续,会使得数据发生混乱
// 不建议使用此功能。
// 有关暂停和后台下载的功能,NSURLSession中会介绍。
if (_downloadOperation.isPaused) {
[_downloadOperationresume];
else
[_downloadOperationpause];
}
检测网络连接状态
AFNetworkReachabilityStatusUnknown = -1, 未知
未连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, 3G
无线连接
// 1. AFNetwork 是根据是否能够连接到baseUrl来判断网络连接状态的
// 提示:最好使用门户网站来判断网络连接状态。
NSURL *url = [NSURLURLWithString:@"http://www.baidu.com"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
_httpClient
[_httpClientsetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 之所以区分无线和3G主要是为了替用户省钱,省流量
// 如果应用程序占流量很大,一定要提示用户,或者提供专门的设置,仅在无线网络时使用!
switch
caseAFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"无线网络");
break;
caseAFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G网络");
break;
caseAFNetworkReachabilityStatusNotReachable:
NSLog(@"未连接");
break;
caseAFNetworkReachabilityStatusUnknown:
NSLog(@"未知错误");
break;
}
}];
加载JSON
官方建议AFN的使用方法
定义一个全局的AFHttpClient:包含有
1> baseURL
请求
操作队列
由AFHTTPRequestOperation负责所有的网络操作请求
// 1. NSURLRequest
NSURLRequest *request = [_httpClientrequestWithMethod:@"GET"path:@"videos.php?format=json"parameters:nil];
// 2. 连接
AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSArray
// 成功之后,直接使用反序列化出来的结果即可。
NSLog(@"%@", JSON);
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id
// 1> 网络访问获取数据出错
// 2> JSON的反序列化出错
NSLog(@"%@ %@", error, JSON);
}];
// 3. 将操作添加到队列,开始多线程操作
// 将操作添加到队列或者start,操作就会启动
[_httpClient.operationQueueaddOperation:op];
// [_queue addOperation:op];
// [op start];
上传图像
/*
此段代码如果需要修改,可以调整的位置
把upload.php改成网站开发人员告知的地址
2. 把file改成网站开发人员告知的字段名
*/
// 1. httpClient->url
// 2. 上传请求POST
NSURLRequest *request = [_httpClientmultipartFormRequestWithMethod:@"POST"path:@"upload.php"parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 在此位置生成一个要上传的数据体
// form对应的是html文件中的表单
/*
参数
要上传的[二进制数据]
对应网站上[upload.php中]处理文件的[字段"file"]
要保存在服务器上的[文件名]
上传文件的[mimeType]
*/
UIImage *image = [UIImage imageNamed:@"头像1"];
NSData *data = UIImagePNGRepresentation(image);
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
// 设置时间格式
dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
[formData appendPartWithFileData:data name:@"file"fileName:fileName mimeType:@"image/png"];
}];
// 3. operation包装的urlconnetion
AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];
setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
NSLog(@"上传完成");
failure:^(AFHTTPRequestOperation *operation, NSError
NSLog(@"上传失败->%@", error);
}];
[_httpClient.operationQueueaddOperation:op];
——断点续传
•设置操作的输出流(在网络中的数据是流的方式传输)
●
•[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:YES]];
–
下载
// 1. 建立请求
NSURLRequest *request = [_httpClientrequestWithMethod:@"GET"path:@"download/Objective-C2.0.zip"parameters:nil];
// 2. 操作
AFHTTPRequestOperation *op = [[AFHTTPRequestOperationalloc] initWithRequest:request];
_downloadOperation = op;
// 下载
// 指定文件保存路径,将文件保存在沙盒中
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0] stringByAppendingPathComponent:@"download.zip"];
op.outputStream = [NSOutputStreamoutputStreamToFileAtPath:path append:NO];
// 设置下载进程块代码
/*
当前一次读取的字节数(100k)
已经下载的字节数(4.9M)
文件总大小(5M)
*/
setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long
// 设置进度条的百分比
CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
NSLog(@"%f", precent);
_progressView.progress
}];
// 设置下载完成操作
setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id
// 下载完成之后,解压缩文件
/*
参数1:要解结压缩的文件名及路径
参数2:要解压缩到的位置,目录 - > document目录
*/
[SSZipArchiveunzipFileAtPath:path toDestination:docs[0]];
// 解压缩之后,将原始的压缩包删除
// NSFileManager专门用于文件管理操作,可以删除,复制,移动文件等操作
// 也可以检查文件是否存在
[[NSFileManagerdefaultManager] removeItemAtPath:path error:nil];
// 下一步可以进行进一步处理,或者发送通知给用户。
NSLog(@"下载成功");
failure:^(AFHTTPRequestOperation *operation, NSError
NSLog(@"下载失败");
}];
// 启动下载
[_httpClient.operationQueueaddOperation:op];