从在线加载图像时的UIActivityIndi​​catorView?

时间:2011-03-10 23:52:03

标签: objective-c xcode ios4 uiimageview uiimage

我有一个简单的脚本,显示在来自互联网的UIImageView中。

有没有办法显示UIActivityIndi​​catorView或类似的东西来向用户显示它正在加载?

这是我的最小代码:

NSString *imagePath = [NSString stringWithFormat:@"urlofimagehere.jpg"];
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imagePath]];
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
[imageView setImage:myimage];
[myimage release];

谢谢! 库尔顿

编辑:删除代码

1 个答案:

答案 0 :(得分:3)

-[NSData initWithContentsOfURL:]

是一种同步方法。这意味着它将阻塞,直到数据通过网络加载。如果您希望能够保持UI响应,则需要使用异步方法。有关详细信息,请阅读:http://akosma.com/2010/05/28/initwithcontentsofurl-methods-considered-harmful/

我建议将NSURLRequest与NSURLRequestDelegate一起使用,以在数据加载完成后接收回调。这是一个例子:

- (void)loadImageAtURL(NSString *)urlString {
    [myUIActivityIndicatorView startAnimating];

    // SHOW NETWORK INDICATOR
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    // SET UP THE REQUEST
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url] autorelease];

    // SET UP THE CONNECTION
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    mutData = [[[NSMutableData alloc] init] retain];
}

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

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data {
    [mutData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {

    // ONCE LOADED HIDE NETWORK INDICATOR
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    // RELEASE THE CONNECTION
    [connection release];

    // CREATE NEW UIIMAGE FROM THE DATA
    image = [[[UIImage alloc] initWithData:mutData] retain];
    [mutData release];

    // HIDE THE ACTIVITY INDICATOR
    // Make sure hidesWhenStopped is set to YES on the activity indicator.
    [myUIActivityIndicatorView stopAnimating];
    [myUIImageView setImage:image];
    [image release];
}

希望这有帮助!