initWithContentsOfURL经常返回nil

时间:2013-03-06 18:26:30

标签: xcode networking nsurlconnection initwithcontentsofurl

NSError *error;
NSString *string = [[NSString alloc]
                    initWithContentsOfURL:URL
                    encoding:NSUTF8StringEncoding
                    error:&error];

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

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

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分:1)

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