AFNetworking是一个为 iOS 和 Mac OSX 制作的令人愉快的网络库,它建立在URL 装载系统框架的顶层,内置在Cocoa里,扩展了强有力的高级网络抽象。它的模块架构被良好的设计,拥有丰富的功能,因此,使用起来,必定赏心悦目。
@介绍
1.支持HTTP请求和基于REST的网络服务(包括GET、POST、 PUT、DELETE等)
2.支持ARC
3.要求iOS 5.0及以上版本
4.UIKit扩展
@配置
1.下载AFNetworking,将2个文件夹:AFNetworking和UIKit+AFNetworking拖入工程
2.导入以下库文件:CFNetwork、Security、SystemConfiguration、MobileCoreServices
3.如果你以前用的是1.0版本,那么AFNetworking 2.0 Migration Guide能帮助你
4.如果你是用CocoaPods配置的,那么
platform:ios,'7.0'
pod"AFNetworking","~>2.0"
@使用
1.HTTP请求操作
AFHTTPRequestOperationManager封装的共同模式与web应用程序通过HTTP通信,包括创建请求,响应序列化,网络可达性监控、运营管理和安全,以及请求。
*GET请求
view source
print
?
1.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
2.
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
3.
NSLog(@"JSON: %@", responseObject);
4.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
5.
NSLog(@"Error: %@", error);
6.
}];
*POST请求
view source
print
?
1.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
2.
NSDictionary *parameters = @{@"foo": @"bar"};
3.
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
4.
NSLog(@"JSON: %@", responseObject);
5.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
6.
NSLog(@"Error: %@", error);
7.
}];
*POST请求(多表)
view source
print
?
01.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
02.
NSDictionary *parameters = @{@"foo": @"bar"};
03.
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
04.
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
05.
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
06.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
07.
NSLog(@"Success: %@", responseObject);
08.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
09.
NSLog(@"Error: %@", error);
10.
}];
2.AFURLSessionManager(NSURLSession详细见网络编程(6))
创建和管理制定的NSURLSession对象NSURLSessionConfiguration对象必须实现<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, <NSURLSessionDelegate>协议
*创建一个下载任务
view source
print
?
01.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
02.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
03.
04.
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
05.
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
06.
07.
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
08.
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
09.
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
10.
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
11.
NSLog(@"File downloaded to: %@", filePath);
12.
}];
13.
[downloadTask resume];
*创建一个上传任务
view source
print
?
01.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
02.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
03.
04.
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
05.
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
06.
07.
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
08.
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
09.
if (error) {
10.
NSLog(@"Error: %@", error);
11.
} else {
12.
NSLog(@"Success: %@ %@", response, responseObject);
13.
}
14.
}];
15.
[uploadTask resume];
*创建一个带多表,进度的上传任务
view source
print
?
01.
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
02.
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
03.
} error:nil];
04.
05.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
06.
NSProgress *progress = nil;
07.
08.
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
09.
if (error) {
10.
NSLog(@"Error: %@", error);
11.
} else {
12.
NSLog(@"%@ %@", response, responseObject);
13.
}
14.
}];
15.
16.
[uploadTask resume];
*创建一个数据流Data任务
view source
print
?
01.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
02.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
03.
04.
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
05.
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
06.
07.
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
08.
if (error) {
09.
NSLog(@"Error: %@", error);
10.
} else {
11.
NSLog(@"%@ %@", response, responseObject);
12.
}
13.
}];
14.
[dataTask resume];
3.网络监测(一般会用另一个网络监测类,Reachability,还有JSON解析方法,反正我也一般不用,自行脑补)
AFNetworkReachabilityManager监控网络领域的可达性,WWAN地址和WiFi接口.
*当前网络状态
view source
print
?
1.
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
2.
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
3.
}];
*HTTP Manager 可达性
view source
print
?
01.
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
02.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
03.
04.
NSOperationQueue *operationQueue = manager.operationQueue;
05.
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
06.
switch (status) {
07.
case AFNetworkReachabilityStatusReachableViaWWAN:
08.
case AFNetworkReachabilityStatusReachableViaWiFi:
09.
[operationQueue setSuspended:NO];
10.
break;
11.
case AFNetworkReachabilityStatusNotReachable:
12.
default:
13.
[operationQueue setSuspended:YES];
14.
break;
15.
}
16.
}];
4.AFHTTPRequestOperation
AFHTTPRequestOperation是使用HTTP或HTTPS协议的AFURLConnectionOperation的子类。
它封装的获取后的HTTP状态和类型将决定请求的成功与否。虽然AFHTTPRequestOperationManager通常是最好的去请求的方式,但是AFHTTPRequestOpersion也能够单独使用。
*GET请求
view source
print
?
01.
NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
02.
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
03.
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
04.
op.responseSerializer = [AFJSONResponseSerializer serializer];
05.
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
06.
NSLog(@"JSON: %@", responseObject);
07.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
08.
NSLog(@"Error: %@", error);
09.
}];
10.
[[NSOperationQueue mainQueue] addOperation:op];
*批量多请求
view source
print
?
01.
NSMutableArray *mutableOperations = [NSMutableArray array];
02.
for (NSURL *fileURL in filesToUpload) {
03.
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
04.
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
05.
}];
06.
07.
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
08.
09.
[mutableOperations addObject:operation];
10.
}
11.
12.
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
13.
NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
14.
} completionBlock:^(NSArray *operations) {
15.
NSLog(@"All operations in batch complete");
16.
}];
17.
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
@其他资料
延伸阅读:
1、iOS网络编程之ASIHTTPRequest框架同步请求
2、iOS网络编程之MBProgressHUD等待指示器
3、iOS网络编程之iOS中Socket编程介绍
4、iOS网络编程之NSStream实现TCP Socket iPhone客户端
5、iOS网络编程之iOS中解析Bonjour服务
6、iOS网络编程之iCloud文档存储编程实例
7、iOS开发网络编程之断点续传NSURLConnection
8、iOS网络编程(六)NSURLSession详解