AFNetworking的POST上传

  1. - (void)download {
  2. // 1.创建网络管理者
  3. // AFHTTPSessionManager 基于NSURLSession
  4. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  5. // 2.利用网络管理者下载数据
  6. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
  7. /*
  8. destination
  9. - targetPath: 系统给我们自动写入的文件路径
  10. - block的返回值, 要求返回一个URL, 返回的这个URL就是剪切的位置的路径
  11. completionHandler
  12. - url :destination返回的URL
  13. */
  14. /*
  15. @property int64_t totalUnitCount; 需要下载文件的总大小
  16. @property int64_t completedUnitCount; 当前已经下载的大小
  17. */
  18. NSProgress *progress = nil;
  19. NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:&progress destination:^ NSURL * (NSURL * targetPath, NSURLResponse * response) {
  20. NSLog(@"targetPath = %@", targetPath.absoluteString);
  21. NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  22. NSString *toPath = [path stringByAppendingPathComponent:response.suggestedFilename];
  23. NSLog(@"toPath = %@", toPath);
  24. return [NSURL fileURLWithPath:toPath];
  25. } completionHandler:^ void(NSURLResponse * response, NSURL * url, NSError * error) {
  26. // NSLog(@"下载完毕 url = %@", url.absoluteString);
  27. }];
  28. // 给Progress添加监听 KVO
  29. [progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
  30. // 3.启动任务
  31. [task resume];
  32. NSLog(@"%lld, %lld", progress.totalUnitCount, progress.completedUnitCount);
  33. }
  34. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(NSProgress *)progress change:(NSDictionary *)change context:(void *)context {
  35. // NSLog(@"%lld, %lld", progress.totalUnitCount, progress.completedUnitCount);
  36. NSLog(@"%f", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
  37. }
0

 

原文地址:https://www.cnblogs.com/dududuzhaoji/p/5473811.html