以下是我下载图书的代码
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath= [resourceDocPath stringByAppendingPathComponent:_bookname];//in _bookname i am already getting the value ,say abcd.pdf
NSLog(@"The bookfilepath is %@",filePath);
NSLog(@"the lenght of recieved data is %d", _recievedData.length);//here i get the correct file size also
[_recievedData writeToFile:filePath atomically:YES];
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: filePath] == YES)
{
flag=1;
NSLog (@"File exists");
}
else
{
NSLog (@"File not found"); //always this happens in the log
}
}
filePath
没有文件存在。为什么?
有趣的部分是_recievedData.length
正在返回正确的文件大小。
答案 0 :(得分:6)
因为您无法写入应用包([[NSBundle mainBundle] resourcePath]
)。
改为写入文档文件夹。
答案 1 :(得分:3)
此代码似乎获取资源路径,剥离最后一个路径组件,然后添加Documents
。这不是到达Documents文件夹的正确方法。相反,请使用NSSearchPathForDirectoriesInDomains
:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:_bookname];