我正在使用以下代码显示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何时完成显示图像?
非常感谢。
答案 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;
}