2015-04-07 86 views
2

我正在使用NSURLSessionDownloadTask下载文件。它会被下载并保存。我可以正常显示数据。关闭应用程序后保存的文件不再存在

不幸的是我只有iOS模拟器才能测试。如果我使用Xcode上的停止按钮关闭应用程序,会发生什么情况。然后我重新启动,该文件不再存在。

但是,如果我通过从应用程序中删除它来关闭它。运行列表通过单击cmd + shift + H两次。并通过点击应用程序来解决它。在模拟器上。我找到了这个文件。

BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:path]; 

这是模拟器问题吗?我不应该在真实的设备上担心它?

其实,我只是设法在iPhone上进行测试。完全一样的行为!任何解释。

我称之为上,我发送了返回目的地保存目的地块NSURLSessionDownloadTask

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request 
              progress:(NSProgress * __autoreleasing *)progress 
              destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination 
            completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler 

目的地块代码:

NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 

回答

2

尝试登录documentsDirectoryURL,你会看到,每次启动应用程序都会有所不同。解决方案是在启动之间保存不是绝对URL,而是相对于NSLibraryDirectory目录的路径。我有同样的问题,我有两个方法解决了这个问题:

// [self uploadFolder] returns a folder in NSLibraryDirectory 
+ (NSString*)relativePathForURL:(NSURL*)url 
{ 
    NSURL *uploadFolderURL = [self uploadFolder]; 
    if ([url.baseURL isEqual:uploadFolderURL]) 
    { 
     return url.relativeString; 
    } 
    else if ([url.absoluteString hasPrefix:uploadFolderURL.absoluteString]) 
    { 
     return [url.absoluteString substringFromIndex:uploadFolderURL.absoluteString.length]; 
    } 
    return nil; 
} 

+ (NSURL*)urlForRelativePath:(NSString*)path 
{ 
    return [NSURL URLWithString:path relativeToURL:[self uploadFolder]]; 
} 

他们应该如下方式使用:

  1. 下载文件,并将其与一些URL savedURL移动到文件夹NSLibraryDirectory。

  2. 拨打电话relativePath = [self relativePathForURL:savedURL]并保存。

  3. 应用程序时在重新启动呼叫savedURL = [self urlForRelativePath:relativePath]

  4. savedURL现在是有效的。

+0

它已经gert保存到NSDocumentDirectory。我更新了问题,请检查 – hasan83

+0

@ hasan83感谢您的澄清。我已经更新了答案。 – Avt

+0

谢谢你的男人。即使我没有测试或使用你的解决方案。但我知道在每一个LibraryDirectory路径都会改变。我的错误是我将文件的完整路径保存在userdefaults中,并在需要时从那里获取。正如你所提到的,我只应该将LibraryDirectory部分保存在完整路径(RelativePath)之后。 – hasan83

0

继承人的解决方案;

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ 

    //location is the temporary "destination" which you returned (can be Temp directory) and it now contains the downloaded file. Now copy the file to a new location (eg documents directory) for future use. 

    BOOL fileCopied = [[[NSFileManager defaultManager] copyItemAtURL:location toURL:documentsDirectoryURLForSavingFileForFutureUe error:&error]; 


    } 
相关问题