AFNetWorking3.0的简单使用
2016-07-08 14:20
429 查看
AFNetWorking3.0的使用
实现GET、POST请求
实现文件、图片上传、下载
检测网络状态
设置请求头数据
[objc] view
plain copy
#import "ViewController.h"
#import "AFNetworking.h"//提供了数据的异步下载功能
#import "UIKit+AFNetworking.h"//常用控件添加了类别,这些控件中使用图片可以异步加载
//UIImageView setImageWithURL
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 实现GET请求(JSON,XML,HTML)
// [self testGet];
// [self testPost];
// [self uploadFile];
// 同步下载
// [self downloadFile];
// 文件异步下载
// [self asyncDownloadFile];
// [self checkNetWorkStatus];
// [self setHTTPHeadField];
}
- (void)setHTTPHeadField{
//抓包做项目
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//添加了请求头 域
[manager.requestSerializer setValue:@"123" forHTTPHeaderField:@"test"];
}
- (void)checkNetWorkStatus{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSArray *array = @[@"未知",@"不可达",@"WAN",@"Wifi"];
NSLog(@"状态 = %@",array[status + 1]);
}];
[manager.reachabilityManager startMonitoring];
}
- (void)asyncDownloadFile{
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(100, 100, 300, 300);
[self.view addSubview: imageView];
//异步加载图片
// imageView setImageWithURL:<#(nonnull NSURL *)#>
//参数2:下载提示图片
// imageView setImageWithURL:<#(nonnull NSURL *)#> placeholderImage:<#(nullable UIImage *)#>
//参数1: 传入图片网址
//参数2: 表示下载提示图片
//参数3: 下载执行block
//参数4: 下载失败block
// imageView setImageWithURLRequest:<#(nonnull NSURLRequest *)#> placeholderImage:<#(nullable UIImage *)#> success:<#^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image)success#> failure:<#^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error)failure#>
__weak typeof(imageView) iv = imageView;
[imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://p2.gexing.com/G1/M00/BD/E8/rBACFFIex5_BUKxwAAAVRVJ7W9I803_200x200_3.jpg"]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
iv.image = image;
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
}];
}
- (void)downloadFile{
NSString *urlString = @"http://d2.eoemarket.com/app0/147/147800/apk/1289732.apk?channel_id=426";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//参数1:网络请求
//参数2;下载进度
//参数3:文件存放位置
//参数4:完成后执行block
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"downloadProgress = %f%%",downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *path = [NSString stringWithFormat:@"%@/Documents/zhihu.apk",NSHomeDirectory()];
NSLog(@"path = %@",path);
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"success");
}];
[task resume];
}
- (void)uploadFile{
NSString *urlString = @"http://quiet.local/upload/upload.php";
NSString *path = [[NSBundle mainBundle] pathForResource:@"20130717220646_FxWvw.jpg" ofType:nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//参数1:网址
//参数3:传入formData,上传数据放里面
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"20130717220646_FxWvw.jpg" mimeType:@"image/jpeg" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"上传进度 = %f",uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)testPost{
// GET和POST都是发起请求的形式
// GET请求的数据在URL的参数中
// POST请求的数据放在请求体中,安全性较高
// 注意:POST类型的请求不要直接放在浏览器中请求
NSString *urlString = @"http://quiet.local/posttest/login.php";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlString parameters:@{@"username":@"test",@"password":@"123"} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)testGet{
NSString *urlString = @"http://www.baidu.com/s";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//参数1:传入网址
//参数2:传入网址的参数
//下载进度
//成功之后执行block
//失败之后执行block
//注意:默认情况下请求获取数据必须是JSON数据,而且content-type:json/appliacation,text/json,如果不是,报—1016错误
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:urlString parameters:@{@"wd":@"kaka"} progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"downloadProgress = %f",downloadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
实现GET、POST请求
实现文件、图片上传、下载
检测网络状态
设置请求头数据
[objc] view
plain copy
#import "ViewController.h"
#import "AFNetworking.h"//提供了数据的异步下载功能
#import "UIKit+AFNetworking.h"//常用控件添加了类别,这些控件中使用图片可以异步加载
//UIImageView setImageWithURL
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 实现GET请求(JSON,XML,HTML)
// [self testGet];
// [self testPost];
// [self uploadFile];
// 同步下载
// [self downloadFile];
// 文件异步下载
// [self asyncDownloadFile];
// [self checkNetWorkStatus];
// [self setHTTPHeadField];
}
- (void)setHTTPHeadField{
//抓包做项目
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//添加了请求头 域
[manager.requestSerializer setValue:@"123" forHTTPHeaderField:@"test"];
}
- (void)checkNetWorkStatus{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSArray *array = @[@"未知",@"不可达",@"WAN",@"Wifi"];
NSLog(@"状态 = %@",array[status + 1]);
}];
[manager.reachabilityManager startMonitoring];
}
- (void)asyncDownloadFile{
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(100, 100, 300, 300);
[self.view addSubview: imageView];
//异步加载图片
// imageView setImageWithURL:<#(nonnull NSURL *)#>
//参数2:下载提示图片
// imageView setImageWithURL:<#(nonnull NSURL *)#> placeholderImage:<#(nullable UIImage *)#>
//参数1: 传入图片网址
//参数2: 表示下载提示图片
//参数3: 下载执行block
//参数4: 下载失败block
// imageView setImageWithURLRequest:<#(nonnull NSURLRequest *)#> placeholderImage:<#(nullable UIImage *)#> success:<#^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image)success#> failure:<#^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error)failure#>
__weak typeof(imageView) iv = imageView;
[imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://p2.gexing.com/G1/M00/BD/E8/rBACFFIex5_BUKxwAAAVRVJ7W9I803_200x200_3.jpg"]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
iv.image = image;
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
}];
}
- (void)downloadFile{
NSString *urlString = @"http://d2.eoemarket.com/app0/147/147800/apk/1289732.apk?channel_id=426";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//参数1:网络请求
//参数2;下载进度
//参数3:文件存放位置
//参数4:完成后执行block
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"downloadProgress = %f%%",downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *path = [NSString stringWithFormat:@"%@/Documents/zhihu.apk",NSHomeDirectory()];
NSLog(@"path = %@",path);
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"success");
}];
[task resume];
}
- (void)uploadFile{
NSString *urlString = @"http://quiet.local/upload/upload.php";
NSString *path = [[NSBundle mainBundle] pathForResource:@"20130717220646_FxWvw.jpg" ofType:nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//参数1:网址
//参数3:传入formData,上传数据放里面
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"20130717220646_FxWvw.jpg" mimeType:@"image/jpeg" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"上传进度 = %f",uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)testPost{
// GET和POST都是发起请求的形式
// GET请求的数据在URL的参数中
// POST请求的数据放在请求体中,安全性较高
// 注意:POST类型的请求不要直接放在浏览器中请求
NSString *urlString = @"http://quiet.local/posttest/login.php";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlString parameters:@{@"username":@"test",@"password":@"123"} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)testGet{
NSString *urlString = @"http://www.baidu.com/s";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//参数1:传入网址
//参数2:传入网址的参数
//下载进度
//成功之后执行block
//失败之后执行block
//注意:默认情况下请求获取数据必须是JSON数据,而且content-type:json/appliacation,text/json,如果不是,报—1016错误
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:urlString parameters:@{@"wd":@"kaka"} progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"downloadProgress = %f",downloadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
相关文章推荐
- 为何 IntelliJ IDEA 比 Eclipse 更好
- 微信支付返回-1的情况和解决方式
- ArrayList源码剖析
- WebRoot与WebContent的区别
- LFM-Latent Factor Model
- 怎么关闭InstantRun
- OpenCV中IplImage, CvMat, Mat 基本使用和元素遍历
- 用Redis存储Tomcat集群的Session
- Android 百分比布局库
- python函数中使用默认参数的坑
- 忘记Ubuntu的登陆密码?这样来重设!
- Linux中不关机扩展磁盘的命令汇总
- so使用的正确方法
- python:functools之partial
- 最小生成树 《啊哈算法》读书笔记
- mybatis在xml文件中处理大于号小于号的方法
- ViewPager+Fragment取消预加载(延迟加载)
- linux批量替换文件内容3种方法(perl,sed,shell)
- 因数分解
- 黑马程序员----面试题之银行调度系统