2015-05-07 28 views
0

這裏是我的代碼下載一本書不能下載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正在返回正確的文件大小。

+2

永遠不會寫'if([filemgr fileExistsAtPath:filePath] == YES)'。 「真」條件可以產生除YES之外的許多值。 'fileExistsAtPath:'是_already_布爾值。寫'if([filemgr fileExistsAtPath:filePath])'。 – matt

回答

6

因爲無法寫入應用程序包([[NSBundle mainBundle] resourcePath])。

改爲寫入文檔文件夾。

+0

看看代碼。 OP正在嘗試寫入「文檔」文件夾。問題在於問題中的代碼在過去有效(即使它從來不是訪問Documents文件夾的正確方式),但它不適用於更新的iOS版本。 – rmaddy

+0

@rmaddy不會寫入文檔文件夾。 – trojanfoe

+0

糟糕 - 我收回它。使用'stringByDeletingLastPathComponent'實際上會給出錯誤的路徑。 – rmaddy

3

看來,這段代碼獲取資源路徑,剝離掉最後一個路徑組件,然後添加Documents。這不是訪問「文檔」文件夾的正確方法。相反,使用NSSearchPathForDirectoriesInDomains

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

在iOS上,您還應該研究文檔以查找應該使用哪個目錄。 NSDocumentDirectory,NSApplicationSupportDirectory,NSCachesDirectory和NSTemporaryDirectory()都有不同的用途。 – gnasher729

+0

我同意。他應該參考[文件系統基礎知識](https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html)並確認文檔是否是正確的文件夾。我從他的代碼示例中推斷出他正在嘗試訪問Documents,所以我只想說明正確的方法。 – Rob