1 下载AFNetworking资源包 https://github.com/AFNetworking/AFNetworking。
2 将AFNetWorking,UIKit+AFNetworking文件夹导入项目
3 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework4 在.pch中加入 #import "AFNetworking.h",#import "UIImageView+AFNetworking.h"(任意地方都可以使用)
Note:
AFJSONOperation,AFPropertyListOperation, AFXMLOperation用来解析结构化数据。
UIImageView+AFNetworking用来快捷的填充image view
AFHTTPClient用来进行更底层的请求
用自定义的AFHTTPClient子类来访问一个web service。
AFNetworkActivityIndicatiorManager用来给用户做出网络访问的提示。
AFImageRequestOperation用来加载图片。
demo
//AFNetWorking异步加载图片
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView = imageView;
[imageView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"1"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(@"获取成功");
_imageView.image = image;
[_imageView setNeedsDisplay];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"获取失败");
}];
[self.view addSubview:imageView];
//Get请求(不带参数)
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//一定要写哦
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://1000phone.net:8088/app/taobao/api/get_cateall.php?app_name=igo" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success is %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error %@",error);
}];
//Get请求(带参数)
// 支持GET URL与参数分开的写法
AFHTTPRequestOperationManager * manager1 = [AFHTTPRequestOperationManager manager];
manager1.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary * paramaters1 = @{@"username":@"test",@"password":@"123456"};
[manager1 GET:@"http://119.255.38.178:8089/sns/my/login.php" parameters:paramaters1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"responseObject is %@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error is %@",error);
}];
//post
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// POST1(相当于get)
[manager POST:@"http://119.255.38.178:8089/sns/my/login.php" parameters:@{@"username":@"test",@"password":@"123456"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"responseObject is %@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
NSData * data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"]];
// POST2(上传)
[manager POST:@"http://119.255.38.178:8089/sns/my/upload_headimage.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:@"headimage" fileName:@"1.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"POST Image Success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"POST Image Error!");
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error is %@",error);
}];
//下载
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dl_dir.qq.com/qqfile/qq/QQforMac/QQ_V2.4.1.dmg"]];
AFHTTPRequestOperation * operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"下载成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"下载失败");
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"%lld %lld %.2f",totalBytesRead,totalBytesExpectedToRead,(CGFloat)totalBytesRead/totalBytesExpectedToRead);
}];
[operation start];
//上传
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://119.255.38.178:8089/sns/my/login.php" parameters:@{@"username":@"test",@"password":@"123456"} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"登录成功");
//必须先登录才能上传头像
AFHTTPRequestSerializer * serializer = [AFHTTPRequestSerializer serializer];
NSData * imgData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"]];
NSMutableURLRequest * request = [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://119.255.38.178:8089/sns/my/upload_headimage.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imgData name:@"headimage" fileName:@"1.png" mimeType:@"image/png"];
} error:nil];
operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传照片成功");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"上传照片失败");
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"%lld %lld %u %.2f",totalBytesWritten,totalBytesExpectedToWrite,bytesWritten,(CGFloat)totalBytesWritten/totalBytesExpectedToWrite);
}];
[operation start];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"登录失败");
}];
//多个请求
NSArray * imgArr = @[@"http://img.app.d1cm.com/news/img/201312021616153719.jpg",
@"http://img1.xcarimg.com/b63/s2515/m_20110718163332702074.jpg",
@"http://img.app.d1cm.com/news/img/201312021610065708.jpg"];
for (int i = 0; i < imgArr.count; i++) {
NSURL * url = [NSURL URLWithString:imgArr[i]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFHTTPResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %ld", [responseObject length]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
}
// 网络状态检测
- (BOOL)isNetWorkReachable
{
AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
// 开启网络监视器
[afNetworkReachabilityManager startMonitoring];
[afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:{
NSLog(@"网络不通");
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi:
{
NSLog(@"网络通过WIFI连接");
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN:{
NSLog(@"网络通过wan连接");
break;
}
default:
break;
}
}];
//断点下载
// 断点续传
NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"QQ.dmg"];
NSLog(@"path is %@",path);
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://dl_dir.qq.com/qqfile/qq/QQforMac/QQ_V2.4.1.dmg"]];
_breakPointOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
_breakPointOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[_breakPointOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"下载进度 %lld %lld",totalBytesRead,totalBytesExpectedToRead);
}];
[_breakPointOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"下载完成");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"下载失败");
}];
[_breakPointOperation start];
return [AFNetworkReachabilityManager sharedManager].isReachable;
}