iPhone - NSURLConnection does not receive data

Posted by Jukurrpa on Stack Overflow See other posts from Stack Overflow or by Jukurrpa
Published on 2010-05-31T15:16:18Z Indexed on 2010/06/09 11:02 UTC
Read the original article Hit count: 189

Hi,

I have a pretty weird problem with NSURLRequest.
I'm using them to make an asynchronous image loading in an UITableView. The first time the tableView displays, all connections from NSURLRequests open correctly but receive absolutely no data, regardless of how long I wait.
But as soon as I scroll down in the tableView, the newly created requests for the new cells work perfectly!

The only way for the images on top of the tableView to load is to make them disappear by scrolling down and then up again, in order to create new requests.

Here is what I do in "cellForRowAtIndexPath":

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];  

if (cell == nil) {  
  cell = [[UITableViewCell alloc] initWIthFrame:CGRectMake(0, 0, 300, 60)];
  AsyncUIImageView imageView = [[AsynUIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
  imageView.tag = IMG_VIEW // an enum for tags

  [cell addSubView:imageView];
  [imageView release];
}

AsyncUIImageView imageView = (AsyncUIImageView*)[cell viewWithTag:IMG_VIEW];

// I do a few cache checks here, but if the image aint cached I do this:
[imageView loadImageFromURL:@"http://someurl.com/somepix.jpg"]; // all urls are different, just an example

The AsyncUIImageView inherits from UIImageView and contains an NSURLConnection which opens upon calling the loadImageFromURL method:

(void) loadImageFromURL:(NSString*)filename  {
 if (self.connection != nil)
    [self.connection release];
 if (self.data != nil)
    [self.data release];

  NSURLRequest* request = [NSURLRequest requestWithURL:[[NSURL alloc] initWithString:fileName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
  self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  if (self.connection == nil)
    return;
  self.data = [[NSMutableData data] retain];
}

I've created the delegate methods "connection: didReceiveData", which appends received data to self.data and "connectionDidFinishLoading" which sets the image and closes the connection once the transfer is complete.
These work, but are never called for the first requests I create.

I suspect this bug to come from the main thread not giving the first requests the control so they can execute themselves, as the same behavior happens if I keep my finger on the screen after a scroll: connections open themselves, but no data is received until I stop touching the screen.
What am I doing wrong?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c