Ios 关闭应用程序后,已保存的文件不再存在
我正在使用NSURLSessionDownloadTask下载文件。它被下载并保存。我可以正常显示数据 不幸的是,我只有iOS模拟器要测试。如果我用Xcode上的停止按钮关闭应用程序,会发生什么。然后我重新启动,文件不再存在 但是,如果我通过从应用程序中删除它来关闭它。通过单击cmd+shift+H两次运行列表。并通过点击应用程序将其重新调校。在模拟器上。我找到文件了Ios 关闭应用程序后,已保存的文件不再存在,ios,ios-simulator,afnetworking-2,nslibrarydirectory,Ios,Ios Simulator,Afnetworking 2,Nslibrarydirectory,我正在使用NSURLSessionDownloadTask下载文件。它被下载并保存。我可以正常显示数据 不幸的是,我只有iOS模拟器要测试。如果我用Xcode上的停止按钮关闭应用程序,会发生什么。然后我重新启动,文件不再存在 但是,如果我通过从应用程序中删除它来关闭它。通过单击cmd+shift+H两次运行列表。并通过点击应用程序将其重新调校。在模拟器上。我找到文件了 BOOL found = [[NSFileManager defaultManager] fileExistsAtPath:pa
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]];
尝试登录
文档directoryurl
,您会发现每次启动应用程序时,它都是不同的。解决方案是在两次启动之间保存的不是绝对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]];
}
它们应按以下方式使用:
savedURL
relativePath=[self-relativePathForURL:savedURL]
并保存它savedURL
现在有效 - (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];
}
它已保存到NSDocumentDirectory。我想问你一个最新的问题check@hasan83谢谢你的澄清。我已经更新了答案。谢谢你。即使我没有测试或使用你的解决方案。但我的想法是,在每个运行库目录路径都会改变。我的错误是,我将文件的完整路径保存在userdefaults中,并在需要时从那里获取它。正如你提到的,我只应该在完整路径(RelativePath)中的LibraryDirectory部分之后保存该部分。