Download the image from the URL in the iPhone only if

I am using initWithContentsOfURL from NSData strong> to load an image from a URL. However, I do not know the size of the image in advance, and I would like the connection to stop or end if the response exceeds a certain size.

Is there a way to do this in iPhone 3.0?

Thanks in advance.

+3
source share
1 answer

You cannot do this directly through NSData, however NSURLConnection will support such a thing by loading the image asynchronously and using the connection: didReceiveData: to check how much data you received. If you go over your limit, just send a cancel message to NSURLConnection to stop the request.

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

@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
+10
source

Source: https://habr.com/ru/post/1713302/


All Articles