我正在开发一个iPhone应用程序,我通过网络服务从其他服务器加载大量数据。
我想在苹果指南的某处读到,对于网络感知应用程序,您必须设置网络超时,之后您已警告用户“网络不可用”。
我该怎么办?
答案 0 :(得分:2)
以下是使用request-timeout = 20设置调用Web Service的示例代码。如果它在20时间内没有响应,那么它将停止连接,我们会得到一个nil数据。
NSString* str = [NSString stringWithFormat:@"http://ws.geonames.org/findNearbyPostalCodes?lat=%f&lng=%f",curr_latitude,curr_longitude];
NSMutableURLRequest* request2=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]];
[request2 setHTTPMethod:@"POST"];
[request2 setTimeoutInterval:20];
NSURLResponse *response=nil;
NSError *err=nil;
NSData *data1=[[NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&err] retain];
if(data1 == nil)
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The network is not available.\n Please check the Internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// It will store all data to data1
// Here you can proceed with data1
}