【问题标题】:initWithContentsOfURL often returns nilinitWithContentsOfURL 通常返回 nil
【发布时间】:2013-02-21 16:52:46
【问题描述】:
NSError *error;
NSString *string = [[NSString alloc]
                    initWithContentsOfURL:URL
                    encoding:NSUTF8StringEncoding
                    error:&error];

当我在我的 iPhone 上测试它时,它总是在我打开 wifi 时工作。但是,当我使用 3G 时,我经常得到零。如果我连续尝试 15 次(我有一个更新按钮),我终于得到了想要的结果。

我的问题是,这个问题是在服务器端还是我的代码不稳定?我应该使用不同的方法来获取更安全的数据吗?

【问题讨论】:

    标签: xcode networking nsurlconnection initwithcontentsofurl


    【解决方案1】:

    你没有提供足够的信息来给出一个模糊的答案,但你确实有一些选择。

    最重要的是,您有一个“error”参数,您应该打印出其结果。您还可以在 NSString 类中使用更好的 API。

    把你的代码改成这样:

    NSError *error = NULL;
    NSStringEncoding actualEncoding;
    
    // variable names in Objective-C should usually start with lower case letters, so change
    // URL in your code to "url", or even something more descriptive, like "urlOfOurString"
    NSString *string = [[NSString alloc] initWithContentsOfURL:urlOfOurString usedEncoding:&actualEncoding error:&error];
    if(string)
    {
        NSLog( @"hey, I actually got a result of %@", string);
    
        if(actualEncoding != NSUTF8StringEncoding)
        {
            // I also suspect the string you're trying to load really isn't UTF8
            NSLog( @"and look at that, the actual encoding wasn't NSUTF8StringEncoding");
        }
    } else {
        NSLog( @"error when trying to fetch from URL %@ - %@", [urlOfOurString absoluteString], [error localizedDescription]);
    }
    

    【讨论】:

    • 对不起,如果我不够清楚,但它实际上总是 UTF8。我会尝试看看这是否会使过程更加稳定。虽然我真的想知道这是否可能是服务器端的问题?
    【解决方案2】:

    我现在改用STHTTPRequest。我非常推荐这个库,易于使用且功能强大。

    【讨论】:

      猜你喜欢
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2013-02-18
      • 2019-06-20
      • 2017-12-16
      相关资源
      最近更新 更多