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);
前もって感謝します..