【问题标题】:NSData not accepting escaped / UTF8 encoded URLNSData 不接受转义/UTF8 编码的 URL
【发布时间】:2012-10-08 16:44:23
【问题描述】:

我正在尝试创建一个包含主包中文件内容的 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

环顾 Google,似乎该 URL 仍未正确编码。有人知道确保编码有效的额外步骤吗?

【问题讨论】:

  • 您可以查看dataWithContentsOfURL:options:error:获取数据时是否出现错误。
  • 是的,只是这样做了,错误已发布。谢谢。

标签: ios nsurl


【解决方案1】:

尝试使用 fileURLWithPath:,类似这样:

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

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

【讨论】:

    【解决方案2】:

    应该没有必要进行百分比转义。您遇到问题的原因是您使用的是URLWithString:,它用于“非文件”网址。

    对于基于文件的 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];
    

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2015-03-07
      • 2013-03-28
      相关资源
      最近更新 更多