iOS之AFNetworking:网络请求资源下载至本地

  • 首先大家要导包儿, 在GitHub上面可以找到


    iOS之AFNetworking:网络请求资源下载至本地_第1张图片
  • 话不多说直接上干货儿, 具体细节小编全在代码中标注:

      //构造资源链接
      NSString *urlString = @"http://img1.sc115.com/uploads/sc/jpg/HD/1/204.jpg";
      NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
      //创建AFN的manager对象
      AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
      //构造URL对象
      NSURL *url = [NSURL URLWithString:urlString];
      //构造request对象
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
      //使用系统类创建downLoad Task对象
      NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
          NSLog(@"%@", downloadProgress);//下载进度
      } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
          //返回下载到哪里(返回值是一个路径)
          //拼接存放路径
          NSURL *pathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
          return [pathURL URLByAppendingPathComponent:[response suggestedFilename]];
      } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
          //下载完成走这个block
          if (!error)
          {
              //如果请求没有错误(请求成功), 则打印地址
              NSLog(@"%@", filePath);
          }
      }];
      //开始请求
      [task resume];
    

你可能感兴趣的:(iOS之AFNetworking:网络请求资源下载至本地)