xcode - initWithContentsOfURL 通常返回 nil

标签 xcode networking nsurlconnection initwithcontentsofurl

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/

相关文章:

objective-c - XCode 中的图像和声音文件在哪里?

C++ Eclipse Mac Hello World

java - 为什么 DatagramSocket 不通过网络发送多播地址?

Swift, SSL 自签名证书 IOS8+

ios - 从另一个 View Controller 停止dispatch_async内部的无限while循环

iphone - 如何找到NSString使用的内存?

iphone - 带有动画的 UIPagecontrol,如 Apple Safari 应用程序

android - 如何在 Cordova 应用程序上检查互联网连接?

networking - Docker容器无法连接到主机: No route to host

swift - 在 Swift 中为 SOAP POST 从 NSURLConnection 迁移到 NSURLSession