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

标签 ios nsurl

我正在尝试创建一个 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/

相关文章:

ios - Objective-C 将 NSURL 传递给另一个 View Controller

macos - startAccessingSecurityScopedResource() 实际上是做什么的?

ios - 用相机胶卷图像填充桌面 View

ios - 在iOS上启动codenameone应用程序时发出警告(“应用程序会降低设备速度”)

ios - 苹果推送通知的分发和开发的区别

ios - ViewForHeaderInSection 代码仅适用于 header 出列

ios - ComputerNode 不显示 Objective-C

cocoa - 沙盒应用程序中的 NSOpenPanel 忽略提供的目录 URL

ios - UIApplication sharedapplication openURL 不工作

java - 自定义 URL 方案作为现有 URL 方案的适配器