timeout stringwithcontentsofurl

你离开我真会死。 提交于 2019-12-03 09:38:37

问题


I have this call to stringwithcontentsofurl:

[NSString stringWithContentsOfURL:url usedEncoding:nil  error:nil];

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.


回答1:


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:.




回答2:


Here's my take on it:

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];


来源:https://stackoverflow.com/questions/3027056/timeout-stringwithcontentsofurl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!