我正在使用NSData的initWithContentsOfURL从 url 加载图像。但是,我事先不知道图像的大小,如果响应超过一定大小,我希望连接停止或失败。
有没有办法在iPhone 3.0 中做到这一点?
提前致谢。
我正在使用NSData的initWithContentsOfURL从 url 加载图像。但是,我事先不知道图像的大小,如果响应超过一定大小,我希望连接停止或失败。
有没有办法在iPhone 3.0 中做到这一点?
提前致谢。
您不能直接通过 NSData 执行此操作,但是NSURLConnection将通过异步加载图像并使用connection:didReceiveData:检查您收到的数据量来支持此类操作。如果您超出限制,只需将取消消息发送到 NSURLConnection 以停止请求。
简单示例:(receivedData 在 header 中定义为 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