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 回答