我有这个对stringwithcontentsofurl的调用:
[NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
Run Code Online (Sandbox Code Playgroud)
我怎么能给出一个简单的超时?我不想使用线程或操作队列(url的内容大约是100个字符),我只是不想在连接缓慢时等待太久.
Chr*_*ris 17
这是我的看法:
NSString* link = @"http://example.com";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse* response=nil;
NSError* error=nil;
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* stringFromServer = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可能最好使用NSURLConnection类方法+sendSynchronousRequest:returningResponse:error:; 它将返回一个数据对象,您可以使用(使用-initWithData:encoding:)初始化您的字符串.您可以通过NSURLRequest使用其-initWithURL:cachePolicy:timeoutInterval:方法创建超时来指定超时,然后将该请求作为第一个参数传递+sendSynchronousRequest:returningResponse:error:.
| 归档时间: |
|
| 查看次数: |
6184 次 |
| 最近记录: |