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

时间:2009-07-23 03:26:30

标签: iphone objective-c cocoa-touch nsdata

我正在使用 NSData initWithContentsOfURL 从网址加载图片。但是,我事先并不知道图像的大小,如果响应超过一定的大小,我希望连接停止或失败。

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

提前致谢。

1 个答案:

答案 0 :(得分: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