How to perform asynchronous request using JSON?

1

Scenario, I have a data request using JSON but would like this request to be made outside of the main thread of the app so that it does not crash and that the user can perform other operations while the data is downloaded.

In the code below I can already download the data normally, but only need to be done on a secondary thread.

-(void)recebeTodosOsDadosPorFuncionarioDoWebService{        
    NSMutableString* strURL =[[NSMutableString alloc]initWithFormat:@"http://localhost/advphp/ArquivosFuncionando/pegaDadosNaoLidosPorFuncionario.php?funcionario=%@",funcionarioCadastrado];           
    NSURL* url = [NSURL URLWithString: strURL];        
    NSData* data = [NSData dataWithContentsOfURL:url];        
    NSError*erro;

    arraySalvaDadosProcessos = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&erro];

    if(arraySalvaDados == (id)[NSNull null]|| [arraySalvaDados count] == 0){

       NSLog(@"Erro para receber dados do webservice: \n\n%@", arraySalvaDados);

    }else{

        [self salvaTodosOsDadosRecebidosNoBancoLocal];
    }
}
    
asked by anonymous 29.10.2014 / 15:44

2 answers

3

A simple way to execute code in the background is by using Grand Central Dispatch (GDC). The dispatch_async method executes a block of code asynchronously and returns immediately, that is, does not block execution in the current stream. You can create your own dispatch queues or use the ones defined by default.

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  //realize aqui o trabalho em background
        dispatch_async(dispatch_get_main_queue(), ^{ 
       //quando as operações em background forem concluídas, execute aqui o código na thread principal para atualização da tela, caso necessário
        });
    }); 
    
29.10.2014 / 17:52
3

Set your class as delegate of <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

Ordering:

-(void)performRequest{  
    NSString * urlConnection = [[NSString alloc] initWithFormat:
                                @"Linkaqui"];
    urlConnection = [urlConnection stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    url = [[NSURL alloc] initWithString: urlConnection];
    request = [NSMutableURLRequest requestWithURL: url
                                      cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                  timeoutInterval: 4000];
    connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];
}

Taking the response and concatenating its receivedResponse of type NSData declared in its class properties:

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

Capturing some error if it occurs:

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"-----> Error %@ <-----", error);
}

When you have finished receiving all the data:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSError       * error     = nil;
    if (receivedResponse != nil && !error) {
        //Chamada assincrona para a manipulação dos dados que obteve com a resposta
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self updatingBackground];
        });
    }else{

    }
}

-(void) updatingBackground{
     //Salva todos os dados que receber/mostra, enfim faz todas as operações
}
    
29.10.2014 / 17:34