我正在尝试创建一个 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
对象对我来说是 nil。该文件肯定包含在我的主包中(因为我能够从一开始就获得 URL)所以我想知道出了什么问题。
编辑:
运行这个:
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL options:NSDataReadingMapped error:&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];
关于ios - NSData 不接受转义/UTF8 编码的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785900/