2011-02-22 11 views
5

Estoy usando un NSURLConnection en un NSThread pero ninguno de los métodos de delegado NSURLConnection se ejecutan! Tengo un método principal en mi subclase NSTread y un ciclo while que mantiene el hilo activo. ¿Alguna ayuda?NSUrlConnection en NSThread - ¡No se ejecuta ningún delegado!

Perdón por todo este código, pero creo que es la mejor manera de describir mi problema. Así que este es un objeto que hace la conexión asincrónica llamando createConnectionWithPath:userObjectReference

@interface WSDAsyncURLConnection : NSObject 
{ 
    NSMutableData *receivedData; 
    NSDate *connectionTime; 
    NSURLConnection *connection; 

    id _theUserObject; 

} 


@property (nonatomic, retain) NSMutableData *receivedData; 
@property (nonatomic, retain) NSDate *connectionTime; 
@property (nonatomic, assign) NSURLConnection *connection; 

- (void)createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject; 


@end 


#import "WSDAsyncURLConnection.h" 

@implementation WSDAsyncURLConnection 
@synthesize connectionTime, receivedData, connection; 


- (void) terminate 
{ 
    if (self.connection) { 
     [self.connection release]; 
     self.connection = nil; 
    } 
} 


- (void) createConnectionWithPath:(NSString *)thePath userObjectReference:(id)userObject; 
{ 
    _theUserObject = userObject; 


    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:thePath] 
               cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60]; 


    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 

    if (self.connection) 
    { 
     /* record the start time of the connection */ 
     self.connectionTime = [NSDate date]; 

     /* create an object to hold the received data */ 
     self.receivedData = [NSMutableData data]; 
    } 
} 


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

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    /* appends the new data to the received data */ 
    [self.receivedData appendData:data]; 
} 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{  
    [self terminate]; 
} 


- (void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // displays the elapsed time in milliseconds 
    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:self.connectionTime]; 
    // displayes the length of data received 
    NSUInteger length = [self.receivedData length]; 

    NSString* aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; 

    [self terminate]; 


    [[NSNotificationCenter defaultCenter] postNotificationName:WSDAsynchURLConnectionDidFinished 
                 object:_theUserObject 
                 userInfo:[NSDictionary dictionaryWithObject:aStr forKey:@"urlResponseString"]]; 

    NSLog(@"ti=%f, l=%d, response=%@", elapsedTime, length, aStr); 

} 

@end 

Este código es en su mayoría de proyecto de ejemplo de una manzana y funciona bien fuera de un NSThread. Pero cuando lo uso en la siguiente subclase de subproceso, ¡no se ejecuta ningún método de delegado!

@implementation IncomingThread 



- (void) main { 

    NSAutoreleasePool *poool = [[NSAutoreleasePool alloc] init]; 


// I start the URLConnection here ... But no delegate is executed ! 
     [urlConn createConnectionWithPath:@"http://localhost:8888" userObjectReference:nil]; 


    while (![self isCancelled]) { 

     [NSThread sleepForTimeInterval:3.]; 
    } 


    [poool release]; 

} 


- (id) init 
{ 
    self = [super init]; 
    if (self != nil) { 

     urlConn = [[WSDAsyncURLConnection alloc] init]; 
    } 
    return self; 
} 


- (void) dealloc { 

    NSLog(@"deallocating (%@)...", [self className]); 


    [urlConn release]; 

    [super dealloc]; 
} 

Respuesta

2

Antes que nada: no necesita usar NSURLConnection en el hilo separado. Como es asíncrono, no bloquea el hilo principal. Segundo: no hay procesamiento de su conexión, ya que siempre se detiene la ejecución de runloop del hilo con esta paz de código:

while (![self isCancelled]) { 
     [NSThread sleepForTimeInterval:3.]; 
    } 

A partir de los documentos para la sleepForTimeInterval:

No run loop processing occurs while the thread is blocked. 
+0

¡Tienes razón! ¡Me lo perdí! ¡Gracias! – Vassilis

+0

xmmm ... Incluso si comento 'sleepForTimeInterval' aún no hay llamadas de delegados. (No lanzo el hilo, excepto si se lanza solo cuando el método 'main' termina pero no!) – Vassilis

+0

Sí, por supuesto, porque el hilo sale inmediatamente. Si desea utilizar un hilo separado, utilice una solicitud sincrónica o haga una asincronía en el hilo principal. – Max

1

Lo estás haciendo de la manera difícil. NSURLConnection no juega muy bien con los hilos, ya que necesita un ciclo de ejecución para funcionar. Su hilo no tiene un ciclo de ejecución y, por lo tanto, el código no funciona. ¿Por qué no ejecutar la conexión en el hilo principal? O puede envolver la conexión en un NSOperation, sample code here. Y hoy en día también tienes la opción de usar una conexión síncrona y enviarla a una cola global de GCD.

+0

Muchas gracias! Echaré un vistazo al código de muestra NSOperation – Vassilis

0

¿Se acordó para asignar el delegado?

Algo así como:

self.connection.delegate = self; 

hecho de que su clase WSDAsyncURLConnection implementa los métodos de delegado, no quiere decir que están siendo llamados.

+0

Pero por supuesto -> 'self.connection = [[NSURLConnection alloc] initWithRequest: theRequest ** delegate: self ** startImmediately: YES];' en el código anterior. Gracias de todos modos. – Vassilis

+0

ah sí, supongo que no lo leí todo :) – Friesgaard

0

tardío pero puede salvar la vida a otros :)

enlace solución es: métodos NSURLConnection Délège no funciona

+0

Perdón por el enlace equivocado, –

+0

http://www.depl0y.com/?p=345 enlace real –

Cuestiones relacionadas