【问题标题】:initWithContentsOfURL:error: returns (null) when the contents are special charactersinitWithContentsOfURL:error: 当内容为特殊字符时返回 (null)
【发布时间】:2012-03-28 17:28:25
【问题描述】:

initWithContentsOfURL:error: 在应该返回 "São Tomé and Príncipe" 时返回 (null)。我已经使用没有特殊字符的文本对其进行了测试,然后效果很好。

NSString *myURL = [NSString stringWithString:@"http://mywebsite.com/api-call.php"];
NSURL *url = [[NSURL alloc] initWithString:myURL];
NSString *strResult = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",strResult);

我猜这个问题与编码有关,但我不知道如何解决它。

【问题讨论】:

  • 返回的是nil,而不是字符串(null)。您是否检查过错误对象以查看其内容? NSError * err; NSString *strResult = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&err]; if( !strResult ){ NSLog(@"%@", err); }
  • 不,我现在就试试。谢谢
  • 它返回:“错误域=NSCocoaErrorDomain 代码=261”。看来我必须检查 API 是否以 UTF-8 编码返回。

标签: objective-c cocoa-touch encoding nsstring


【解决方案1】:

感谢Iulius Caesar 我发现我的文档没有以 UTF-8 编码返回数据。

我修改了 php 文件,将header('Content-Type: text/html; charset=UTF-8'); 添加到代码顶部并将其保存为 UTF-8 格式的文件。现在可以了!

【讨论】:

    猜你喜欢
    • 2016-12-08
    • 2020-07-06
    • 2012-07-29
    • 2021-07-08
    • 2013-12-07
    • 1970-01-01
    • 2016-02-23
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多