2013-02-13 54 views
3

我想單擊一個按鈕開始下載圖像,並在更新後將我的UIImageView更新爲新圖像。我的代碼的問題是它只下載東西,而不是更新。它只會更新,如果我再次點擊它。 我希望它在未來的某個時候更新圖像,當圖像下載時。我怎麼做?如何使用塊異步下載圖像?

編輯:我找到了錯誤的代碼,改變它有點幫助,它都可以工作。 還有另外一個問題 - 我怎麼簡化這段代碼而不會把它弄亂?它看起來過度。

- (IBAction)getImage 
{ 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
    ^{ 
     NSURL *imageURL = [NSURL URLWithString:@"http://example.com/1.jpg"]; 
     __block NSData *imageData; 

     dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
      ^{ 
       imageData = [NSData dataWithContentsOfURL:imageURL]; 


       dispatch_sync(dispatch_get_main_queue(), ^{ 
              self.image = [UIImage imageWithData:imageData]; 
             }); 
            }); 


    }); 

    self.imageView.image = self.image; 
} 

回答

18

您正在設置imageView在圖像完成下載之前,您需要將邏輯移動到塊中。此外,您還沒有理由在dispatch_async的範圍內額外添加dispatch_sync

- (IBAction)getImage 
{ 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
    ^{ 
     NSURL *imageURL = [NSURL URLWithString:@"http://example.com/1.jpg"]; 
     NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 

     //This is your completion handler 
     dispatch_sync(dispatch_get_main_queue(), ^{ 
      //If self.image is atomic (not declared with nonatomic) 
      // you could have set it directly above 
      self.image = [UIImage imageWithData:imageData]; 

      //This needs to be set here now that the image is downloaded 
      // and you are back on the main thread 
      self.imageView.image = self.image; 

     }); 
    }); 

    //Any code placed outside of the block will likely 
    // be executed before the block finishes. 
} 
+0

嗨,我正在研究相同的代碼。我需要知道如何訪問此塊內的自我,因爲屬性只能在getter/setter形式的塊內部訪問。在這裏使用self.imageView.image會給你一個錯誤。請讓我知道你是如何爲這個imageView創建一個屬性的。請參閱我的代碼。 http://stackoverflow.com/questions/23890573/access-the-control-inside-the-synchronous-block-in-xcode-5-0-iphone – 2014-05-27 14:00:02

2

退房https://github.com/rs/SDWebImage

我用它來下載圖像與進度通知的背景。它可以簡單地添加到您的項目使用Cocoapods(http://cocoapods.org)。

在Cocoapods和GitHub上還有其他幾種異步圖像加載器,如果這對您不適用。

0

這是我一直在使用的,雖然它沒有提供任何我認爲常常有用的進展。這很簡單。

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *image))completionBlock 
{ 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
           if (!error) 
           { 
            completionBlock(YES,data); 
            NSLog(@"downloaded FULL size %lu",(unsigned long)data.length); 
           } else{ 
            completionBlock(NO,nil); 
           } 
          }]; 
}