AFNetworking的数据请求和下载

AFNetworking框架运用非常方便,能节省很多的代码量,今天用它来请求一下数据,还有运用它的下载功能。
1.请求数据

  
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //创建一个管理对象
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
        
        //1.URL
        
        NSString *urlPath = @"https://api.douban.com/v2/movie/top250";
        
        //    NSURL *url = [ NSURL URLWithString:urlPath];
        
        //2.发送一个请求体
        [manager POST:urlPath parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"task = %@",task);
            //响应体数据
            NSLog(@"response object = %@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"task = %@",task); 
        }];
    });

得到的数据是json数据格式的。

2.下载数据
当然先要在info.plist中打开网络请求 ATSS -AAL (简写)

- (IBAction)downLoad:(UIButton *)sender {
    //1.manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //2.url设置
    NSURL *url = [NSURL URLWithString:@"http://wl.baidu190.com/1470730340/20160879819642dc26a12e0bfc0dc55fda98d5.mp3"];
    //3.请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //4.下载任务
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //
        //监听下载进度 --downloadProgress
        NSLog(@"downlodProgress%f",downloadProgress.fractionCompleted);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //返回一个保存路径,保存到沙盒中
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"Documents/1.mp3"];
        
        return [NSURL URLWithString:path];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"response = %@", response);
        NSLog(@"url = %@", filePath);
    }];
    
    //resume
    [task resume];
}
下载数据.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,009评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 2009年,M君就在不经意间闯入小野的世界。没有一点征兆。 第一次上学,小野就迟到了,她发高烧第二天才到校。她悄悄...
    Lily小姐阅读 344评论 0 1
  • 神技能✨
    koppa阅读 263评论 2 1
  • 因为最近想写篇关于狗的小说,而我自己又没有养过狗,于是就冠冕堂皇地给自己买了票,去看了这部《一条狗的使命》,顺便奖...
    有鹿689阅读 332评论 0 2