无法下载 ios 中的文件

Can't download a file in ios

这是我下载一本书的代码

- (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 返回了正确的文件大小。

因为您无法写入应用程序包 ([[NSBundle mainBundle] resourcePath])。

改为写入文档文件夹。

看来这段代码获取了资源路径,剥离了最后一个路径组件,然后添加了 Documents。这不是进入 Documents 文件夹的正确方法。相反,使用 NSSearchPathForDirectoriesInDomains:

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath      = [documentsPath stringByAppendingPathComponent:_bookname];