2012-07-23 20 views
6

intenté hacer - [NSString stringWithContentsOfURL: codificación: Error:] asíncrona, mediante la ejecución a un sincrónicamente desde un subproceso en segundo plano:Hacer stringWithContentsOfURL asincrónico - ¿Es seguro?

__block NSString *result; 
dispatch_queue_t currentQueue = dispatch_get_current_queue(); 

void (^doneBlock)(void) = ^{ 
    printf("done! %s",[result UTF8String]); 
}; 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 
             (unsigned long)NULL), ^(void) { 
    result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"] encoding:NSUTF8StringEncoding error:nil]; 
    dispatch_sync(currentQueue, ^{ 
     doneBlock(); 
    }); 
}); 

Su funcionamiento muy bien, y lo más importante, su asíncrona.

Mi pregunta es si es seguro hacer esto, ¿o podría haber problemas de subprocesos, etc.?

Gracias de antemano :)

Respuesta

27

Eso debe ser seguro, pero ¿por qué reinventar la rueda?

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; 
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    // etc 
}]; 
+0

aplausos! No sabía que esto era posible: P – JonasG

+0

Primero pensé que esto funcionaría en la cola principal debido a '[NSOperationQueue mainQueue]', pero que vi 'sendAsynchronousRequest'. Así que esto no debería detener la actualización de la interfaz de usuario. –

0

También puede utilizar:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

dispatch_async(queue, ^{ 
     NSError *error = nil; 
     NSString *searchResultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:searchURL] 
                  encoding:NSUTF8StringEncoding 
                   error:&error]; 
     if (error != nil) { 
      completionBlock(term,nil,error); 
     } 
     else 
     { 
      // Parse the JSON Response 
      NSData *jsonData = [searchResultString dataUsingEncoding:NSUTF8StringEncoding]; 
      NSDictionary *searchResultsDict = [NSJSONSerialization JSONObjectWithData:jsonData 
                       options:kNilOptions 
                       error:&error]; 
      if(error != nil) 
      { 
       completionBlock(term,nil,error); 
      } 
      else 
      { 

       //Other Work here 
      } 
     } 
    }); 

Pero sí, debe ser seguro. Sin embargo, me han dicho que use NSURLConnection debido a llamadas de error y tal cuando se comunican a través de Internet. Todavía estoy investigando esto.

0
-(void)loadappdetails:(NSString*)appid { 
    NSString* searchurl = [@"https://itunes.apple.com/lookup?id=" stringByAppendingString:appid]; 

    [self performSelectorInBackground:@selector(asyncload:) withObject:searchurl]; 

} 
-(void)asyncload:(NSString*)searchurl { 
    NSURL* url = [NSURL URLWithString:searchurl]; 
    NSError* error = nil; 
    NSString* str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; 
    if (error != nil) { 
     NSLog(@"Error: %@", error); 
    } 
    NSLog(@"str: %@", str); 
}