如何异步从服务器获取图像

时间:2013-09-30 12:07:03

标签: iphone ios web-services uiimageview uialertview

我正在做以下事情从服务器加载我的图像。但问题是,当alertview关闭时,imageview会在5-7秒后出现。

如何解决这个问题?

 - (void)showFullImage :(id) sender
   {    
   // for loading view
  self.loading_alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"LOADING",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
  [self.loading_alert show];
  UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(125, 65, 30, 30)];
  indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;

  //indicator.center = CGPointMake(loading_alert.bounds.size.width / 2, loading_alert.bounds.size.height - 50);
  [indicator startAnimating];
  [self.loading_alert addSubview:indicator];      

  self.image_url = [self.question_set valueForKey:@"image_url"];

//--------Asyncronously fetch image----------------------------------------
  NSURL *URL = [NSURL URLWithString:image_url];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
                                                   timeoutInterval:60.0];
  [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

    NSLog(@"1",nil);
    imgView= [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480) ];

     UIImage* queImage = [UIImage imageWithData:data];

UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,42,320,420)];
iv.image = queImage;

[imgView addSubview:iv];    
[self.view addSubview:imgView];  

    //dismiss alert view on main thread
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        // dismiss alert view...
         NSLog(@"2",nil);
        [self.loading_alert dismissWithClickedButtonIndex:0 animated:YES];
    });

}];    
}

帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

忘记GCD,您可以在 NSURLConnection的 sendAsynchronousRequest:queue:completionHandler:方法的队列参数中传递 [NSOperationQueue mainQueue] >,所以你不需要考虑主线程和后台线程,它会在后台自动处理调用请求并在主线程上返回数据。

以下是您的代码的样子:

NSURL *URL = [NSURL URLWithString:image_url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly timeoutInterval:60.0];

// request is called asynchronously and response completion handler will be called on main thread
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

    // do your whatever work here as you do normally, because it's in main thread
    NSLog(@"1",nil);
    imgView= [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480) ];

    UIImage* queImage = [UIImage imageWithData:data];

    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,42,320,420)];
    iv.image = queImage;

    [imgView addSubview:iv];
    [self.view addSubview:imgView];
}

答案 1 :(得分:0)

您需要在主队列中的后台队列和UI更新中下载图像。

像这样使用GCD,

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

        NSURL *URL = [NSURL URLWithString:image_url];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
                                                   timeoutInterval:60.0];
  [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

    NSLog(@"1",nil);


     UIImage* queImage = [UIImage imageWithData:data];

            dispatch_async(dispatch_get_main_queue(), ^{

                imgView= [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480) ];
                if([receivedView isKindOfClass:[UIImageView class]])
                {
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,42,320,420)];
iv.image = queImage;

[imgView addSubview:iv];    
[self.view addSubview:imgView];  
                }
 // dismiss alert view...
         NSLog(@"2",nil);
        [self.loading_alert dismissWithClickedButtonIndex:0 animated:YES];

            });


        }


    });

答案 2 :(得分:0)

SDWebmage - >这是一个很好的第三方库,用于加载图像。

相关问题