我正在使用 NSData 的 initWithContentsOfURL 从网址加载图片。但是,我事先并不知道图像的大小,如果响应超过一定的大小,我希望连接停止或失败。
有没有办法在 iPhone 3.0中执行此操作?
提前致谢。
答案 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