【发布时间】:2009-07-23 03:26:30
【问题描述】:
我正在使用 NSData 的 initWithContentsOfURL 从 url 加载图像。但是,我事先不知道图像的大小,如果响应超过一定大小,我希望连接停止或失败。
有没有办法在 iPhone 3.0 中做到这一点?
提前致谢。
【问题讨论】:
标签: iphone objective-c cocoa-touch nsdata
我正在使用 NSData 的 initWithContentsOfURL 从 url 加载图像。但是,我事先不知道图像的大小,如果响应超过一定大小,我希望连接停止或失败。
有没有办法在 iPhone 3.0 中做到这一点?
提前致谢。
【问题讨论】:
标签: iphone objective-c cocoa-touch nsdata
您不能直接通过 NSData 执行此操作,但是 NSURLConnection 将通过异步加载图像并使用 connection:didReceiveData: 来检查您的数据量来支持这样的事情已收到。如果超出限制,只需将 cancel 消息发送到 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
【讨论】: