2012-06-13 2 views
3

Я начинаю программировать на IOS. Мой вопрос заключается в том, что мое приложение извлекает данные из JSON на моем веб-сервере, при запуске приложений оно немного отстает и задерживается из-за процесса получения, поэтому я хочу показывать индикатор активности при подключении к данным JSON. Как я могу это сделать?Индикатор активности при извлечении данных JSON

Моя JSON кодирования:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSURL *urlAddress = [NSURL URLWithString:@"http://emercallsys.webege.com/RedBoxApp/getEvents.php"]; 
    NSStringEncoding *encoding = NULL; 
    NSError *error; 

    NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error]; 
    NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding]; 

    NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error]; 
    if (dict) 
    { 
     eventsDetail = [[dict objectForKey:@"eventsDetail"] retain]; 
    } 

    [jsonreturn release]; 
} 

ответ

3

использовать следующий код

//add a UIActivityIndicatorView to your nib file and add an outlet to it 
[indicator startAnimating]; 
indicator.hidesWhenStopped = YES; 

dispatch_queue_t queue = dispatch_get_global_queue(
                DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
dispatch_async(queue, ^{ 
    //Load the json on another thread 
    NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL]; 
    [jsonreturn release];   
    //When json is loaded stop the indicator 
    [indicator performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:YES]; 
}); 
+0

спасибо за ответ .. это работает отлично в мои приложения для входа и других страниц. но у меня все еще есть проблема, когда я использовал его для tableView. После того, как я реализую эти методы, я вызываю [[self tableView] reloadData] ;, tableView был перезагружен, но мое изображение в tableCell не появилось. Я использовал asyncimageview.h для ленивой загрузки изображения. – Simon

+0

Вы нашли решение проблемы с UITableView? – SteBra

1

Вы можете использовать что-то вроде ниже код:

- (void)fetchData 
{ 
    [activityIndicator startAnimating]; 

    NSURL *url = [NSURL URLWithString:strUrl]; 

    NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url]; 

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

    if(theConnection) { 

    } 
    else { 
     NSLog(@"The Connection is NULL"); 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    webData = [[NSMutableData data] retain]; 
} 

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"ERROR with theConenction %@",error); 
    UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:@"Information !" message:@"Internet/Service Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    [connectionAlert show]; 
    [connectionAlert release]; 

    [connection release]; 
    [webData release]; 

    return; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    //NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; 
    //NSLog(@"Received data :%@",theXML); 
    //[theXML release]; 

    NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error]; 

    if (dict) { 
     eventsDetail = [[dict objectForKey:@"eventsDetail"] retain]; 
    } 

    [activityIndicator stopAnimating]; 
} 
Смежные вопросы