2013-03-06 60 views
2
NSError *error; 
NSString *string = [[NSString alloc] 
        initWithContentsOfURL:URL 
        encoding:NSUTF8StringEncoding 
        error:&error]; 

当我在我的iPhone上测试它时,它始终工作,当我有WiFi打开。但是,当我在3G上时,我经常得到零。如果我连续尝试15次(我有一个更新按钮),我终于得到了期望的结果。initWithContentsOfURL通常返回零

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

回答

1

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

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]); 
} 
+0

对不起,如果我不够清楚,但是,它实际上是UTF8,总是。我会试着看看这是否能让这个过程更加稳定。虽然我真的想知道它是否会成为服务器端的问题? – Mathias 2013-03-08 18:19:31