2012-03-27 191 views
3

我有一個文件路徑,我需要在NSData中獲取文件的數據。我使用:NSData dataWithContentOfFile返回nil?

NSError *err = nil; 
NSData *d = [NSData dataWithContentsOfFile:file options:nil error:&err]; 

NSLog(@"error: %@", err); 

錯誤是:

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x34a8f0 {NSFilePath=file://localhost/var/mobile/Applications/A19223D4-0AEF-4677-8EDD-0D2CA9A7BB73/Documents/12-03-25%2022:10:48--cc.mp4, NSUnderlyingError=0x34a560 "The operation couldn’t be completed. No such file or directory"} 

但文件/目錄不存在的,因爲我在播放視頻文件,它工作得很好:

MPMoviePlayerViewController *controller = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:[video filepath]]]; 
[self presentMoviePlayerViewControllerAnimated:controller]; 

是什麼出錯了? 謝謝

回答

6

您正在將字符串格式的URL傳遞給dataWithContentsOfFile,您必須使用文件的「文件路徑」。

在這種情況下,您必須從字符串中刪除「file:// localhost」。如果文件存在,那應該起作用。

+0

在NSString上有一個方便的方法可以讓我刪除file:// localhost – 0xSina 2012-03-27 19:16:56

+6

不要簡單地刪除「file:// localhost」前綴。使用'NSString * path = [[NSURL URLWithString:file] path];'將文件URL轉換爲unix路徑。 – 2012-03-27 19:21:57

+0

是的,在NSURL類中你有[url path]。但你有url作爲字符串,所以你必須首先創建url:NSURL * url = [NSURL URLWithString:yourURLString] – LuisEspinoza 2012-03-27 19:26:24