是否存在UIImage完成加载的事件

时间:2013-12-02 08:49:21

标签: ios objective-c uiimage

我正在使用以下代码显示UIImage视图:

NSURL *imageUrl = [[NSURL alloc]initWithString:@"http://..."];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageUrl];
UIImage *audioArt =[[UIImage alloc] initWithData:imageData];
UIImageView *artView =[[UIImageView alloc] initWithImage:audioArt];

artView.contentMode = UIViewContentModeScaleAspectFit;
artView.autoresizesSubviews = NO;
artView.frame = viewRef.bounds;
[artView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[artView setBackgroundColor:[UIColor blackColor]];

[viewRef setBackgroundColor:[UIColor blackColor]];
[viewRef addSubview:artView];

在Objective C中是否有一个事件告诉UIImage何时完成加载或者UIImageView何时完成显示图像?

非常感谢。

2 个答案:

答案 0 :(得分:4)

.h

@interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>

@property (nonatomic) NSMutableData *imageData;
@property (nonatomic) NSUInteger totalBytes;
@property (nonatomic) NSUInteger receivedBytes;

在某个地方打电话

NSURL *imageUrl = [[NSURL alloc]initWithString:@"http://..."];
NSURLRequest *request = [NSURLRequest requestWithURL: imageUrl];
NSURLConnection *connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

并实现委托方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
    NSDictionary *dict = httpResponse.allHeaderFields;
    NSString *lengthString = [dict valueForKey:@"Content-Length"];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *length = [formatter numberFromString:lengthString];
    self.totalBytes = length.unsignedIntegerValue;

    [self.imageData = [[NSMutableData alloc] initWithLength:self.totalBytes];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.imageData appendData:data];
    self.receivedBytes += data.length;

    // Actual progress is self.receivedBytes / self.totalBytes
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    imageView.image = [UIImage imageWithData:self.imageData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //handle error
}

<强>更新

由于NSMutableData initWithLength:创建的数据对象的原始数据用零填充,因此只需将initWithLength:替换为init即可。

答案 1 :(得分:1)

UIImage没有任何委托或回调告诉您成功加载。

如果您从任何网址获取图片,您可以使用NSURL的代理人和通知来跟踪您是否收到了图片。

你也可以实现它:

- (void)loadImage:(NSString *)filePath {
    [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:filePath];
}

- (void)loadImageInBackground:(NSString *)filePath {
   @autoreleasepool{
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
        [self performSelectorOnMainThread:@selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES];
    }
}

- (void)didLoadImageInBackground:(UIImage *)image {
    self.imageView.image = image;
}