2012年8月9日星期四

Asynchronous NSURLConnection with NSOperation

     When I work on NSURLConnection with NSOperation today, I alloc a NSURLConnection like this

NSURLConnection* connection = [[NSURLConnection alloc] 
initWithRequest:urlRequest delegate:self];
And implements the delegate methods, but it seems that those
methods are not called at all. I search the problem in stackOverflow 
for some time and find a blog(here) that helps me know and solve the issue.
"If you are performing this on a background thread, the thread is 
probably exiting before the delegates can be called."
So I follow codes in that blog and modify code in my NSOperation object 
to keep the runloop form exiting is to just put it in an infinite loop:
- (void) start
{
  if (![self isCancelled])
  {
    connection_ = [[NSURLConnection alloc] initWithRequest: 
                          [NSURLRequest requestWithURL:download_.url  
                          cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
                          timeoutInterval:15] delegate:self]; 
    if (connection_ != nil)     
   { 
      [self willChangeValueForKey:@"isExecuting"]; 
      executing_ = YES; 
      [self didChangeValueForKey:@"isExecuting"]; 
    }    
    else 
    {       
      [self willChangeValueForKey:@"isExecuting"]; 
      finished_ = YES; 
      [self didChangeValueForKey:@"isExecuting"]; 
    } 
    while(!finished_) 
    { 
      [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode 
                               beforeDate:[NSDate distantFuture]]; 
    } 
  }
  else
  {
// If it's already been cancelled, mark the operation as finished.
    [self willChangeValueForKey:@"isFinished"]; 
    { 
      finished_ = YES; 
    } 
    [self didChangeValueForKey:@"isFinished"]; 
  }
}
This works well now :)



------
My new business with my wife, wholesale meddle-to-high end men's seamless underwear in the Netherlands: https://ecosharelife.com

没有评论:

发表评论