AFNetworking的数据请求和下载

96
hunterzhu
2016.08.13 20:59* 字数 84

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
日记本
Web note ad 1