Load image from url in iPhone, only if small

10,888

You can't do it directly via NSData however NSURLConnection would support such a thing by loading the image asynchronously and using connection:didReceiveData: to check how much data you have received. If you go over your limit just send the cancel message to NSURLConnection to stop the request.

Simple example: (receivedData is defined in the header as NSMutableData)

@implementation TestConnection

- (id)init {
    [self loadURL:[NSURL URLWithString:@"http://stackoverflow.com/content/img/so/logo.png"]];
    return self;
}

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

    if (conn) {
        receivedData = [[NSMutableData data] retain];
    } else {
        return FALSE;
    }

    return TRUE;
}

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

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

    if ([receivedData length] > 5120) { //5KB
        [conn cancel];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    // do something with the data
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);

    [receivedData release];
}

@end
Share:
10,888
hpique
Author by

hpique

iOS, Android & Mac developer. Founder of Robot Media. @hpique

Updated on June 04, 2022

Comments

  • hpique
    hpique almost 2 years

    I'm using initWithContentsOfURL of NSData to load an image from a url. However, I don't know the size of the image beforehand, and I would like to the connection to stop or fail if the response exceeds a certain size.

    Is there a way to do this in iPhone 3.0?

    Thanks in advance.

  • Mike Abdullah
    Mike Abdullah almost 15 years
    Correct, this is the only Cocoa-level way of doing this on the iPhone. Note that it is asynchronous, whereas your original code is synchronous. Asynchronous is almost always better, but a different approach to get used to.