Xcode 设置NSData DATA WITHCONTENTS URL超时
因此,我的应用程序中有一个方法,如果我的应用程序内容可用,则返回BOOL和updateXcode 设置NSData DATA WITHCONTENTS URL超时,xcode,nsurlconnection,nsdata,ios9,nsurlsession,Xcode,Nsurlconnection,Nsdata,Ios9,Nsurlsession,因此,我的应用程序中有一个方法,如果我的应用程序内容可用,则返回BOOL和update - (BOOL)isUpdateAvailable{ NSData *dataResponse=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"url that returns json object"] ]; if(dataResponse!=nil){ NSError *error; dicUpdat
- (BOOL)isUpdateAvailable{
NSData *dataResponse=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"url that returns json object"] ];
if(dataResponse!=nil){
NSError *error;
dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error];
}
if(dicUpdates.count > 0) isUpdateAvailable = YES;
else isUpdateAvailable = NO;
return isUpdateAvailable;
}
我需要一个同步请求,因为下一个视图控制器将依赖于服务器响应。然而,有时服务器需要很长时间才能响应,或者互联网速度非常慢,我需要设置一个超时,以防止应用程序“被冻结”
我以前使用NSUrlconnection来完成此任务,但它已被弃用
此外,我还尝试使用NSURLSession(也在后台线程中使用它下载更新),但我只知道它是否可以用于同步请求
你知道怎么处理吗?我只需要一个同步方法,它返回一个
BOOL
。致以最诚挚的问候。我们必须在NSURLSession中使用NSURLRequest来设置超时间隔。
检查以下代码:
- (BOOL)isUpdateAvailable{
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"url that returns json object"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4]//timeout
completionHandler:^(NSData *dataResponse,
NSURLResponse *response,
NSError *error) {
// handle response
if(dataResponse!=nil){
NSError *error;
dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error];
}
if(dicUpdates.count > 0) isUpdateAvailable = YES;
else isUpdateAvailable = NO;
return isUpdateAvailable;
}] resume];
}
我有错误,因为return
returnisupdateavailable代码>位于完成处理程序内,我已将其移到会话任务外。我马上试试代码,谢谢!这不起作用,因为该方法返回isUpdateAvailable变量,甚至不等待requestwithURL方法,