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

Jim*_*ery 5 objective-c uiimage ios

我正在使用以下代码显示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];
Run Code Online (Sandbox Code Playgroud)

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

非常感谢.

Mut*_*awe 4

在你的.h

@interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>

@property (nonatomic) NSMutableData *imageData;
@property (nonatomic) NSUInteger totalBytes;
@property (nonatomic) NSUInteger receivedBytes;
Run Code Online (Sandbox Code Playgroud)

并在某个地方打电话

NSURL *imageUrl = [[NSURL alloc]initWithString:@"http://..."];
NSURLRequest *request = [NSURLRequest requestWithURL: imageUrl];
NSURLConnection *connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
Run Code Online (Sandbox Code Playgroud)

并实现委托方法

- (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
}
Run Code Online (Sandbox Code Playgroud)

更新:

由于NSMutableData initWithLength:创建了一个原始数据填充为零的数据对象,因此替换initWithLength:为 justinit即可工作。