ios将NSURL转换成filepath

来源:互联网 发布:建立数据透视表的步骤 编辑:程序博客网 时间:2024/06/07 02:17

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

+(void) doDownload:(NSString*)localFilePath{    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];         NSString *servicePath = [NSString stringWithFormat:DOWNLOAD_RESUME_FILE_URL, [enterpriseId stringByAppendingPathExtension:@"zip"]];    NSURL *URL = [NSURL URLWithString:servicePath];    NSURLRequest *request = [NSURLRequest requestWithURL:URL];        // targetPath是下载的临时文件路径,:app_dir/tmp/CFNetworkDownload_9z499O.tmp    NSURL* (^destinationBlock) (NSURL *targetPath, NSURLResponse *response) = ^NSURL* (NSURL *targetPath, NSURLResponse *response){        return [NSURL fileURLWithPath:localFilePath];// 下载文件最终存放地址,不同于targetPath    };        // filePath即上面那个block的返回值    void (^completionBlock) (NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error){                NSFileManager *fileManager = [NSFileManager defaultManager];                NSString *zipFilePath = [filePath path];// 将NSURL转成NSString                        if([fileManager fileExistsAtPath:zipFilePath]){            [fileManager removeItemAtPath:zipFilePath error:nil];        }    };        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:destinationBlock completionHandler:completionBlock];    [downloadTask resume];}

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

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

0 0