首页 > 解决方案 > 将文件下载到文档路径后,iOS AFNetworking 3.0 文件不存在

问题描述

我正在尝试使用 AFnetworking 从我的服务器下载 json 文件。我遵循官方示例代码。下载 json 后,我需要使用这个 json 与其他本地做一些事情。当我用我的路径获取这个 json 文件时,我总是得到 nil。下面是我的代码

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    if(!error){
        NSLog(@"File downloaded to: %@", filePath);

        if([[NSFileManager defaultManager] fileExistsAtPath:filePath.absoluteString]){
            NSLog(@"file exists");
        } else {
            NSLog(@"file not exists");
        }

    }else{
        NSLog(@"download error %@",error);
    }
}];
[downloadTask resume];

你看我添加了一个逻辑来检查文件是否存在。请求总是成功但不存在文件。文件路径将以 file:///var/... 我怎样才能取回这个 json 文件?

标签: iosdownloadafnetworking-3

解决方案


调用时尝试使用filePath.path而不是filePath.absoluteStringfileExistsAtPath

FileManager 需要传递一个文件 URL


推荐阅读