NSData的dataWithContentOfFile方法返回nil?

4
我有一个文件路径,需要获取该文件的NSData数据。我正在使用以下代码:
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];

什么出了问题?感谢。
1个回答

7

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

在这种情况下,你需要从字符串中删除"file://localhost"。如果文件存在,那么应该可以工作。


NSString中是否有便捷的方法可以让我删除file://localhost? - 0xSina
8
不要仅仅删除 "file://localhost" 前缀。使用 NSString *path = [[NSURL URLWithString:file] path]; 将文件 URL 转换为 Unix 路径。 - Nikolai Ruhe
是的,在NSURL类中你有[url path]。但是你需要将URL作为字符串,所以你首先需要创建URL,如下:NSURL *url = [NSURL URLWithString:yourURLString]。 - LuisEspinoza
@LuisEspinoza 这就是我写的,或者我漏掉了什么吗? - Nikolai Ruhe
@NikolaiRuhe 是的...它们是同一件事...当我写这个评论时,我的 Web 视图没有刷新您的评论。 ;) - LuisEspinoza
啊,抱歉听起来有点不满意 :) - Nikolai Ruhe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接