Ios NSData不接受转义/UTF8编码的URL

Ios NSData不接受转义/UTF8编码的URL,ios,nsurl,Ios,Nsurl,我正在尝试创建一个NSData对象,该对象包含主捆绑包中的文件内容 NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"]; NSURL *chordURL = [NSURL URLWithString:[chordPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSData *chor

我正在尝试创建一个NSData对象,该对象包含主捆绑包中的文件内容

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL URLWithString:[chordPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];
在使用
stringByAddingPercentEscapesUsingEncoding
之前,我得到了一个nil URL,因此我继续并通过重新编码字符串修复了这个问题。现在我得到了一个有效的URL,但是
chordImageData
对象对我来说是零。该文件肯定包含在我的主捆绑包中(因为我可以首先获得URL),所以我想知道出了什么问题

编辑:

运行此:

NSData*chordImageData=[NSData dataWithContentsOfURL:chordURL选项:NSDataReadingMapped错误:&dataCreationError]

为错误获取以下信息:

po dataCreationError
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x7530a00

环顾谷歌,似乎URL的编码仍然不正确。有人知道确保编码有效的其他步骤吗?

尝试使用fileURLWithPath:,类似于:

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL fileURLWithPath: chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];

应该没有必要这样做。出现问题的原因是您使用的是
URLWithString:
,它用于“非文件”URL

对于基于文件的URL,应使用:

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL fileURLWithPath:chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];

您可以检查在通过
dataWithContentsOfURL:options:error:
获取数据时是否发生任何错误。是的,就是这样做的,错误已发布。谢谢