NSURLConnection 验证
我正在尝试验证连接是否成功,但得到的结果不稳定。当我尝试使用虚假网址执行同步请求时:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}
它会挂起一段时间,最终返回:
did_send = FALSE;
但是如果我使用虚假网址执行异步请求:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self ];
if (conn)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}
我
did_send = TRUE;
每次都会得到:。我需要让异步请求正常工作,因为我能够设置超时,而不必在请求超时且默认超时持续时间(异步请求无法更改)时挂起 60 秒。有什么想法吗?
I am trying to validate weather the connection was successful but have been getting inconstant results. When I try to do an synchronous request using a bogus url with:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}
It hangs for a while an eventually returns:
did_send = FALSE;
But if I do an asynchronous request using a bogus url with:
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self ];
if (conn)
{
did_send = TRUE;
}
else
{
did_send = FALSE;
}
I get:
did_send = TRUE;
every time. I need to get the asynchronous request working because I am able to set a timeout and not have to hang for 60 sec while the request times out with the default time out duration that is unchangeable with the asynchronous requests. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 nsurlconnection 类委托方法 connection:didFailWithError: 这应该会为您提供一致的结果。
Try using the nsurlconnection class delegate method connection:didFailWithError: This should give you consistent results.
简单地实例化
NSURLConnection
不会执行任何操作。它创建该类的一个实例,但不开始数据传输——即使请求无法满足,该对象通常也将是非零。相反,您的委托对象(代码中的
self
)需要实现NSURLConnectionDelegate
(它将处理诸如“传入数据”或“错误条件”之类的回调。)然后您必须向NSURLConnection
实例发送-start
消息,这会将其调度到执行线程的运行循环上。有关
NSURLConnectionDelegate
协议的更多信息(包括有关回调中执行的操作的信息),请参阅 Apple 的“URL 加载系统编程指南。"Simply instantiating
NSURLConnection
does nothing. It creates an instance of that class but does not begin the data transfer--the object will generally be non-nil even if the request is impossible to satisfy.Rather, your delegate object (
self
in your code) needs to implementNSURLConnectionDelegate
(which will handle callbacks such as "incoming data" or "error condition.") Then you must send theNSURLConnection
instance the-start
message, which will schedule it on the executing thread's run loop.For more information on the
NSURLConnectionDelegate
protocol (including information on what to do in your callbacks), see Apple's "URL Loading System Programming Guide."