0

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

前もって感謝します..

4

2 に答える 2

0
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];       

この行は呼び出しを同期呼び出しにします。

これを使って

-(void)downloadWithNsurlconnection
{

   //MAke your request here and to call it async use the code below
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:    (NSCachedURLResponse *)cachedResponse {
    return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    //Here in recieved data is the output data call the parsing from here and go on
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
于 2013-11-11T11:06:32.243 に答える
0

これは、非同期URLリクエストを送信する方法です

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];

        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
        {
            if ([data length] > 0 && error == nil)
              //date received 
            else if ([data length] == 0 && error == nil)
                //date empty
            else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
                //request timeout
            else if (error != nil)
                //error
        }];
于 2013-11-11T11:12:31.470 に答える