我正在使用 JSON 从 Web 服务获取数据。问题是当我调用 Web 服务时,由于响应缓慢,我的应用程序在几秒钟内无响应,有时会崩溃。
我搜索了很多,发现通过异步调用而不是同步调用可以解决问题。但是如何使用我不知道的异步调用。
我的代码就像..
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = @"/Get_NearbyLocation_list";
double d1=[[[NSUserDefaults standardUserDefaults]valueForKey:@"LATITUDE"] doubleValue];
NSLog(@"%f",d1);
double d2=[[[NSUserDefaults standardUserDefaults]valueForKey:@"LONGITUDE"] doubleValue];
NSLog(@"%f",d2);
NSString *requestString = [NSString stringWithFormat:@"{\"current_Lat\":\"%f\",\"current_Long\":\"%f\"}",d1,d2];
NSLog(@"request string:%@",requestString);
// NSString *requestString = [NSString stringWithFormat:@"{\"GetAllEventsDetails\":\"%@\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:@"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(@"URL : %@",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];
[request setHTTPMethod: @"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Internet connection is not Available!" message:@"Check your network connectivity" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alt performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
[alt release];
[customSpinner hide:YES];
[customSpinner show:NO];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(@" %@",responseString);
NSDictionary *results = [[responseString JSONValue] retain];
NSLog(@" %@",results);
提前致谢..