AFNetWorking3.0的简单使用

AFNetWorking3.0的使用
实现GET、POST请求
实现文件、图片上传、下载
检测网络状态
设置请求头数据

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #import "ViewController.h"  
  2.   
  3. #import "AFNetworking.h"//提供了数据的异步下载功能  
  4.   
  5. #import "UIKit+AFNetworking.h"//常用控件添加了类别,这些控件中使用图片可以异步加载  
  6. //UIImageView setImageWithURL  
  7.   
  8. @interface ViewController ()  
  9.   
  10. @end  
  11.   
  12. @implementation ViewController  
  13.   
  14. - (void)viewDidLoad {  
  15.     [super viewDidLoad];  
  16.     // Do any additional setup after loading the view, typically from a nib.  
  17.       
  18. //    实现GET请求(JSON,XML,HTML)  
  19. //    [self testGet];  
  20.       
  21. //    [self testPost];  
  22.       
  23. //    [self uploadFile];  
  24. //    同步下载  
  25. //    [self downloadFile];  
  26. //    文件异步下载  
  27. //    [self asyncDownloadFile];  
  28.       
  29. //    [self checkNetWorkStatus];  
  30.   
  31. //    [self setHTTPHeadField];  
  32. }  
  33. - (void)setHTTPHeadField{  
  34.   
  35.     //抓包做项目  
  36.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  37.     //添加了请求头 域  
  38.     [manager.requestSerializer setValue:@"123" forHTTPHeaderField:@"test"];  
  39.       
  40. }  
  41. - (void)checkNetWorkStatus{  
  42.   
  43.     AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];  
  44.       
  45.     [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {  
  46.         NSArray *array = @[@"未知",@"不可达",@"WAN",@"Wifi"];  
  47.         NSLog(@"状态 = %@",array[status + 1]);  
  48.     }];  
  49.     [manager.reachabilityManager startMonitoring];  
  50. }  
  51. - (void)asyncDownloadFile{  
  52.   
  53.     UIImageView *imageView = [[UIImageView alloc] init];  
  54.     imageView.frame = CGRectMake(100100300300);  
  55.     [self.view addSubview: imageView];  
  56.     //异步加载图片  
  57. //    imageView setImageWithURL:<#(nonnull NSURL *)#>  
  58.       
  59.     //参数2:下载提示图片  
  60. //    imageView setImageWithURL:<#(nonnull NSURL *)#> placeholderImage:<#(nullable UIImage *)#>  
  61.       
  62.     //参数1:   传入图片网址  
  63.     //参数2:   表示下载提示图片  
  64.     //参数3:   下载执行block  
  65.     //参数4:   下载失败block  
  66. //    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#>  
  67.       
  68.       
  69.     __weak typeof(imageView) iv = imageView;  
  70.     [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) {  
  71.           
  72.         iv.image = image;  
  73.           
  74.     } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {  
  75.           
  76.     }];  
  77.       
  78. }  
  79. - (void)downloadFile{  
  80.   
  81.     NSString *urlString = @"http://d2.eoemarket.com/app0/147/147800/apk/1289732.apk?channel_id=426";  
  82.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  83.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  84.     //参数1:网络请求  
  85.     //参数2;下载进度  
  86.     //参数3:文件存放位置  
  87.     //参数4:完成后执行block  
  88.     NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:^(NSProgress * _Nonnull downloadProgress) {  
  89.         NSLog(@"downloadProgress = %f%%",downloadProgress.fractionCompleted * 100);  
  90.     } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {  
  91.         NSString *path = [NSString stringWithFormat:@"%@/Documents/zhihu.apk",NSHomeDirectory()];  
  92.         NSLog(@"path = %@",path);  
  93.         return [NSURL fileURLWithPath:path];  
  94.     } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {  
  95.         NSLog(@"success");  
  96.     }];  
  97.     [task resume];  
  98.       
  99. }  
  100. - (void)uploadFile{  
  101.   
  102.     NSString *urlString = @"http://quiet.local/upload/upload.php";  
  103.     NSString *path = [[NSBundle mainBundle] pathForResource:@"20130717220646_FxWvw.jpg" ofType:nil];  
  104.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  105.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  106.     //参数1:网址  
  107.     //参数3:传入formData,上传数据放里面  
  108.     [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {  
  109.           
  110.         [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"20130717220646_FxWvw.jpg" mimeType:@"image/jpeg" error:nil];  
  111.           
  112.     } progress:^(NSProgress * _Nonnull uploadProgress) {  
  113.         NSLog(@"上传进度 = %f",uploadProgress.fractionCompleted);  
  114.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
  115.         NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
  116.         NSLog(@"str = %@",str);  
  117.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
  118.         NSLog(@"error = %@",error);  
  119.     }];  
  120.       
  121. }  
  122. - (void)testPost{  
  123.   
  124.     //  GET和POST都是发起请求的形式  
  125.     //  GET请求的数据在URL的参数中  
  126.     //  POST请求的数据放在请求体中,安全性较高  
  127.     //  注意:POST类型的请求不要直接放在浏览器中请求  
  128.     NSString *urlString = @"http://quiet.local/posttest/login.php";  
  129.       
  130.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  131.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  132.     [manager POST:urlString parameters:@{@"username":@"test",@"password":@"123"} progress:^(NSProgress * _Nonnull uploadProgress) {  
  133.           
  134.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
  135.         NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
  136.         NSLog(@"str = %@",str);  
  137.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
  138.          NSLog(@"error = %@",error);  
  139.     }];  
  140.       
  141. }  
  142.   
  143. - (void)testGet{  
  144.   
  145.     NSString *urlString = @"http://www.baidu.com/s";  
  146.     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  
  147.     //参数1:传入网址  
  148.     //参数2:传入网址的参数  
  149.     //下载进度  
  150.     //成功之后执行block  
  151.     //失败之后执行block  
  152.     //注意:默认情况下请求获取数据必须是JSON数据,而且content-type:json/appliacation,text/json,如果不是,报—1016错误  
  153.     manager.responseSerializer = [AFHTTPResponseSerializer serializer];  
  154.     [manager GET:urlString parameters:@{@"wd":@"kaka"} progress:^(NSProgress * _Nonnull downloadProgress) {  
  155.         NSLog(@"downloadProgress = %f",downloadProgress.fractionCompleted);  
  156.     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  
  157.         NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
  158.         NSLog(@"str = %@",str);  
  159.     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {  
  160.         NSLog(@"error = %@",error);  
  161.     }];  
  162.       
  163. }  
  164. - (void)didReceiveMemoryWarning {  
  165.     [super didReceiveMemoryWarning];  
  166.     // Dispose of any resources that can be recreated.  
  167. }  
  168.   
  169. @end
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值