= $u_time + 86400) { $modifiedDate = get_the_modified_time('F jS, Y'); echo 'Última modificación: '.$modifiedDate.''; } }?>

Asynchronous WebService API Request en iOS

Hoy vamos a hacer una petición a la API de OMDb. Para ello yo he optado por usar un SearchBar por lo que lanzo la petición desde el método  delegado correspondiente:

– (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

Primero nuestras constantes:

#define MAX_TIMEOUT 10
#define ERROR_TIMEOUT @"timed out"
#define API_URL   @"http://www.omdbapi.com/?plot=short&r=json&s="

Creamos nuestra petición con la dirección: http://www.omdbapi.com/?s=her

NSString *title = searchBar.text;
NSString *url = [NSString stringWithFormat:@"%@%@",API_URL,title];
NSURL *restURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:restURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:MAX_TIMEOUT];

 

Creamos una cola de operaciones:  Para ampliar información: Apple Reference

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

 

Y finalmente nuestra llamada:

Aunque a primera vista puede parecer que repetimos mucho código es inevitable si queremos distinguir entre los distintos errores que se pueden dar.

Si la respuesta que nos devuelve no tiene error y tiene datos rellenamos y procesamos la respuesta. Seguidamente EN EL HILO PRINCIPAL recargamos nuestra tabla (SIEMPRE HAY QUE HACER CUALQUIER COSA QUE IMPLIQUE LA UI EN EL HILO PRINCIPAL).

[NSURLConnection sendAsynchronousRequest:request
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) {
         
         if (error == nil){
             if ([data length] >0) {
                 BOOL correctData = [self fillTableWithData:data];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (correctData) {
                         [self.tableView reloadData];
                         [spinner stopAnimating];
                     }
                     else{
                         [spinner stopAnimating];
                         UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Title" message:error_json_parser delegate:self cancelButtonTitle:OK_BUTTON otherButtonTitles:nil];
                         myAlert.delegate = self;
                         [myAlert show];
                     }
                 });
             }
             else{
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [spinner stopAnimating];
                     UIAlertView *myAlert = [CommonUtilities alertWithTitle:nil Message:error_empty_response CancelButton:OK_BUTTON];
                     myAlert.delegate = self;
                     [myAlert show];
                 });
             }
         }
         
         else{
             dispatch_async(dispatch_get_main_queue(), ^{
                 [spinner stopAnimating];
                 if ([[error description] containsString:ERROR_TIMEOUT]) {
                     NSString *msj = [NSString stringWithFormat:@"%@%@",NSLocalizedString(error_request, nil),[error description]];
                     UIAlertView *myAlert = [CommonUtilities alertWithoutLocalizedStringWithTitle:nil Message:msj AndCancelButton:OK_BUTTON];
                     myAlert.delegate = self;
                     [myAlert show];

                 }
                 
             });
         }
     }];

 

Y finalmente: Si bien es cierto que estamos bloqueando la UI con un UIActivityIndicatorView este tutorial es para ilustrar cómo se hace la llamada asíncrona a la API.

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString *title = searchBar.text;
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = self.view.center;
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];

    // Create the URL to make the rest call.
    NSString *url = [NSString stringWithFormat:@"%@%@",API_URL,title];
    NSURL *restURL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:restURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:MAX_TIMEOUT];
    
    //allocate a new operation queue
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    //Loads the data for a URL request and executes a handler block on an
    //operation queue when the request completes or fails.
    
    [NSURLConnection sendAsynchronousRequest:request
     queue:queue
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error) {
         
         if (error == nil){
             if ([data length] >0) {
                 BOOL correctData = [self fillTableWithData:data];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (correctData) {
                         [self.tableView reloadData];
                         [spinner stopAnimating];
                     }
                     else{
                         [spinner stopAnimating];
                         UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Title" message:error_json_parser delegate:self cancelButtonTitle:OK_BUTTON otherButtonTitles:nil];
                         myAlert.delegate = self;
                         [myAlert show];
                     }
                 });
             }
             else{
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [spinner stopAnimating];
                     UIAlertView *myAlert = [CommonUtilities alertWithTitle:nil Message:error_empty_response CancelButton:OK_BUTTON];
                     myAlert.delegate = self;
                     [myAlert show];
                 });
             }
         }
         
         else{
             dispatch_async(dispatch_get_main_queue(), ^{
                 [spinner stopAnimating];
                 if ([[error description] containsString:ERROR_TIMEOUT]) {
                     NSString *msj = [NSString stringWithFormat:@"%@%@",NSLocalizedString(error_request, nil),[error description]];
                     UIAlertView *myAlert = [CommonUtilities alertWithoutLocalizedStringWithTitle:nil Message:msj AndCancelButton:OK_BUTTON];
                     myAlert.delegate = self;
                     [myAlert show];

                 }
                 
             });
         }
     }];
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *