Carga de datos externos en el iPhone SDK

En el iPhone SDK no es posible cargar datos desde URLs externas (NSData, AVAudioPlayer, etc.). Todos los métodos initWithContentsOfURL ó *WithContentsOfURL  reportarán que no han leído nada… La única forma es utilizar la clase NSURLConnection e implementar varios métodos delegados que son los responsables de la descarga de datos empaquetados en un objeto NSMutableData. Ejemplo:

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 
NSMutableData *receivedData = [[NSMutableData data] retain]; 

 
Métodos delegados:

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning];

 
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response { 
    [receivedData setLength:0]; 

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

 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]); 
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; 
    NSLog(aStr); 
    [receivedData release]; 

This entry was posted on Miércoles, Enero 7th, 2009 at 23:15 and is filed under Programación. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply