带有内容的超时字符串 [英] timeout stringwithcontentsofurl
问题描述
我有这个对 stringwithcontentsofurl 的调用:
I have this call to stringwithcontentsofurl:
[NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
我怎样才能给它一个简单的超时时间?我不想使用线程或操作队列(url的内容大约是100个字符),我只是不想在连接慢的时候等待太久.
How can I give that a simple timeout? I don't want to use threads or operation queues (the content of the url is about 100 characters), I just don't want to wait too long when the connection is slow.
推荐答案
在这种情况下,您最好使用 NSURLConnection
类方法 +sendSynchronousRequest:returningResponse:error:代码>;它会返回一个数据对象,你可以用它来初始化你的字符串(使用
-initWithData:encoding:
).您可以通过使用 -initWithURL:cachePolicy:timeoutInterval:
方法创建 NSURLRequest
来指定超时,然后将该请求作为 +sendSynchronousRequest:returningResponse 的第一个参数传递:错误:
.
In this case, you might be best off using the NSURLConnection
class method +sendSynchronousRequest:returningResponse:error:
; it'll return a data object you can initialize your string with (using -initWithData:encoding:
). You can specify a timeout by creating an NSURLRequest
using its -initWithURL:cachePolicy:timeoutInterval:
method, then pass that request as the first parameter of +sendSynchronousRequest:returningResponse:error:
.
这篇关于带有内容的超时字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!