在iPhone中加载来自网址的图片,仅限小

hpi*_*que 3 iphone cocoa-touch objective-c nsdata

我使用initWithContentsOfURLNSData的从URL中加载图像.但是,我事先并不知道图像的大小,如果响应超过一定大小,我希望连接停止或失败.

有没有办法在iPhone 3.0中执行此操作?

提前致谢.

Tra*_*ins 10

您不能通过NSData直接执行此操作,但NSURLConnection将通过异步加载图像并使用connection:didReceiveData:来检查您收到的数据量来支持此类操作.如果超过限制,只需将取消消息发送到NSURLConnection即可停止请求.

简单示例:(receivedData在标头中定义为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
Run Code Online (Sandbox Code Playgroud)