NSError *error;
NSString *string = [[NSString alloc]
initWithContentsOfURL:URL
encoding:NSUTF8StringEncoding
error:&error];
当我在 iPhone 上测试此功能时,当我打开 wifi 时,它总是可以工作。然而,当我使用 3G 时,我经常得不到任何信息。如果我连续尝试 15 次(我有一个更新按钮),我最终会得到想要的结果。
我的问题是,这个问题是服务器端的问题还是我的代码不稳定?我应该使用不同的方法来更安全地获取数据吗?
最佳答案
您没有提供足够的信息,只能给出一个模糊的答案,但您确实有一些选择。
最重要的是,您有一个“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]);
}
关于xcode - initWithContentsOfURL 通常返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15255129/