在iPhone中从网址加载图片,只有小 [英] Load image from url in iPhone, only if small

查看:147
本文介绍了在iPhone中从网址加载图片,只有小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using initWithContentsOfURL of NSData to load an image from a url. However, I don't know the size of the image beforehand, and I would like to the connection to stop or fail if the response exceeds a certain size.

有在 iPhone 3.0中执行此操作的方法

Is there a way to do this in iPhone 3.0?

提前感谢。

推荐答案

您不能通过NSData直接执行,但 NSURLConnection 会通过异步加载映像并使用 connection:didReceiveData:以检查您收到的数据量。如果你超过你的限制只是发送取消消息到NSURLConnection停止请求。

You can't do it directly via NSData however NSURLConnection would support such a thing by loading the image asynchronously and using connection:didReceiveData: to check how much data you have received. If you go over your limit just send the cancel message to NSURLConnection to stop the request.

简单的例子: as NSMutableData)

Simple example: (receivedData is defined in the header as 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

这篇关于在iPhone中从网址加载图片,只有小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆