Search code examples
objective-ciosnsurlconnectiondelay

Method Sleep Until Notification


Is there any way that I can have a method sleep until a notification is posted? This is for an asynchronous NSURLConnection. I cannot move to a synchronous connection for multiple reasons.


Solution

  • Methods cannot "sleep"; that only applies to threads. Just split the code that needs to wait out into another method and have that method called when the notification arrives.

    - (void) doStuffBeforeConnection {
    
        [self doPreConnectionStuff];
    
        NSURL * url = [NSURL URLWithString:@"/U/R/L"];
    
        NSURLRequest * request = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                             timeoutInterval:0];
        NSURLConnection * conn = [NSURLConnection connectionWithRequest:request
                                                             delegate:self];
    
        return;
        // We are now "waiting"...
    }
    
    - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
        [self nowDoStuffThatNeededToWait:response];
    }