Master Stroke
Master Stroke

Reputation: 5128

NSData returning 0 bytes

I am trying to load the image in the following way. But when I call my loadImageFromURL:(NSURL*)inURL function as [self loadImagesFromURL:url] in my tableView its showing 0 bytes. How to get the value of (delta)NSData in my tableview?, which is declared as global...

NSURLConnection* connection;
NSMutableData* delta;

- (void)loadImageFromURL:(NSURL*)inURL {
    NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];

    if (conn) {
        delta = [[NSMutableData data] retain];
    }    
}

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

    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz; 

}

Upvotes: 2

Views: 1168

Answers (1)

Kristian Glass
Kristian Glass

Reputation: 38540

You're getting confused by the asynchronicity. If loadImageFromURL: were synchronous, e.g. wrapping sendSynchronousRequest:returningResponse:error:, your code would work as you would expect; loadImageFromURL: would block while fetching, and return when delta was populated.

However, this is all asynchronous, so what you actually need to do is implement connectionDidFinishLoading: in your delegate (which in this case is self) and have it set cell.imageView.image there.

Rewriting some of your code accordingly (I assume that you removed extraneous code in tableView:cellForRowAtIndexPath: for the purpose of this example):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz;
}

Check out the URL Loading System Programming Guide on NSURLConnection for more details / examples.

Upvotes: 5

Related Questions