有谁知道在什么情况下初始化 NSURLConnection
会返回 nil 而不是创建的连接。文档说这是可能的,但没有具体说明何时发生。
有问题的方法/消息:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-
根据 NSURLConnection
类引用:
Return Value: The URL connection for the URL request. Returns nil if a connection can't be initialized.
URL Loading System Programming Guide 说明如下:
If NSURLConnection can’t create a connection for the request, initWithRequest:delegate: returns nil.
-
虽然此方法有可能返回 nil,但我无法想出触发此方法的场景。我尝试了以下场景:
-
带有空 url 的
URLRequest
:connection:didFailWithError:
调用委托(delegate)方法时出现“不支持的 URL”错误。URLRequest
具有无效的 url:connection:didFailWithError:
委托(delegate)方法被调用,错误为“错误的 URL”。URLRequest
with nonexistent url:connection:didFailWithError:
调用委托(delegate)方法时出现“找不到具有指定主机名的服务器”。作为错误。- 有效请求但没有互联网:
connection:didFailWithError:
调用委托(delegate)方法时显示“Internet 连接似乎处于离线状态。”作为错误。 - 无请求:导致崩溃。
initWithRequest
方法在每个场景(除了最后一个)中返回一个有效的 NSURLConnection
并调用 connection:didFailWithError:
错误。
有没有人能够弄清楚哪种情况会导致返回 nil?
最佳答案
我相信这也可以在加载失败时使用,而不仅仅是初始化。 (alloc 是单独完成的 - 这就是低内存可能会咬你的地方)所以(我猜)它可能会失败,因为你没有可用的网络(3G/Wifi)或者它只是失败了连接到服务器。无论如何,请使用:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
得到真正的失败。
您可以在没有网络的情况下进行模拟 - 或者甚至给它一个错误的 URL。
关于iphone - NSURLConnection 的 initWithRequest 什么时候返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3978020/