How to perform asynchronous request using JSON?

Asked

Viewed 272 times

1

Scenario, I have a data request using JSON but I would like this request to be performed outside the main thread of the app, so that it does not catch 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 I only need it to be done in 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];
    }
}

2 answers

3

Sets its class as delegate of <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

Making the requisition:

-(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 answer and concatenating into your receivedResponse of the kind NSData declared on its class properties:

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

Capturing an error if it occurs:

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

When you finish 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
}
  • I pointed out the solution of @Rafaelleão as the correct one because it is practical, but yours is also viable and good! Thank you very much!

  • @Tiagoamaral without problems, by programming best practice is you use a class delegate to make the requests and get the answers. Unless your case is something very specific somewhere in your project.

3


A simple way to execute background code is by using Grand Central Dispatch (GDC). The dispatch_async method executes a code block asynchronously and returns immediately, that is, it does not block execution in the current stream. You can create your own Dispatch queues or use those 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
        });
    }); 
  • Thanks @Rafaelleão I will test here the code you gave me and return with the answer!

  • It worked perfectly, Now explain one thing to me, when the app is terminated, this process is terminated together, or it turns into a zombie process?

  • When the app is terminated all your threads are also.

  • Thanks again @Rafaelleão

Browser other questions tagged

You are not signed in. Login or sign up in order to post.