NSData dataWithContentOfFile返回nil?

0xS*_*ina 3 cocoa-touch objective-c nsdata ios

我有一个文件路径,我需要在NSData中获取该文件的数据.我在用:

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

NSLog(@"error: %@", err);
Run Code Online (Sandbox Code Playgroud)

错误是:

 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"}
Run Code Online (Sandbox Code Playgroud)

但文件/目录确实存在,因为我正在播放视频文件,它工作得很好:

MPMoviePlayerViewController *controller = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:[video filepath]]];
[self presentMoviePlayerViewControllerAnimated:controller];
Run Code Online (Sandbox Code Playgroud)

出了什么问题?谢谢

Lui*_*oza 6

您正在将字符串格式的URL传递给dataWithContentsOfFile,您必须使用该文件的"文件路径".

在这种情况下,您必须从字符串中删除"file:// localhost".如果文件存在,那应该有效.

  • 不要简单地删除"file:// localhost"前缀.使用`NSString*path = [[NSURL URLWithString:file] path];`将文件URL转换为unix路径. (8认同)