ios将NSURL转换成filepath

今天用AFNetworking做了下载文件的功能,但是API的返回类型是NSURL,在网上搜索了与NSString相互转换的代码,记录一下,删除了无关代码:

 

  1.  
    +(void) doDownload:(NSString*)localFilePath
  2.  
    {
  3.  
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  4.  
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  5.  
     
  6.  
    NSString *servicePath = [NSString stringWithFormat:DOWNLOAD_RESUME_FILE_URL, [enterpriseId stringByAppendingPathExtension:@"zip"]];
  7.  
    NSURL *URL = [NSURL URLWithString:servicePath];
  8.  
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  9.  
     
  10.  
    // targetPath是下载的临时文件路径,:app_dir/tmp/CFNetworkDownload_9z499O.tmp
  11.  
    NSURL* (^destinationBlock) (NSURL *targetPath, NSURLResponse *response) = ^NSURL* (NSURL *targetPath, NSURLResponse *response){
  12.  
    return [NSURL fileURLWithPath:localFilePath];// 下载文件最终存放地址,不同于targetPath
  13.  
    };
  14.  
     
  15.  
    // filePath即上面那个block的返回值
  16.  
    void (^completionBlock) (NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error){
  17.  
     
  18.  
    NSFileManager *fileManager = [NSFileManager defaultManager];
  19.  
     
  20.  
    NSString *zipFilePath = [filePath path];// 将NSURL转成NSString
  21.  
     
  22.  
    if([fileManager fileExistsAtPath:zipFilePath]){
  23.  
    [fileManager removeItemAtPath:zipFilePath error:nil];
  24.  
    }
  25.  
     
  26.  
    };
  27.  
     
  28.  
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:destinationBlock completionHandler:completionBlock];
  29.  
    [downloadTask resume];
  30.  
    }


将NSString转成NSURL的API是fileURLWithPath,从NSURL转成NSString的API是path

 

AFNetworking的核心API,需要传2个回调block作为参数,在我的注释里解释了含义,文档里也有。另外要注意,2个block都是跑在UI Thread里的

posted @ 2018-08-28 09:43  sundaysios  阅读(2048)  评论(0)    收藏  举报