加载图像从URL中的iPhone,只有当小(Load image from url in iPhon

2019-06-26 14:27发布

我使用的NSDatainitWithContentsOfURL从URL中加载图像。 不过,我不知道该图像的大小事先和我想的连接停止或失败,如果响应超过一定规模。

有没有办法在iPhone 3.0做到这一点?

提前致谢。

Answer 1:

你不能直接做它通过NSData的但是NSURLConnection的将通过异步加载图像和使用连接支持这样的事情: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


文章来源: Load image from url in iPhone, only if small