2014-07-23 113 views
3

似乎這應該是相對簡單的。我正在使用適用於iOS的AWS開發工具包(v2),我正嘗試下載.png文件並將其顯示到UIImage中的屏幕上。一切真的有用!只是很奇怪......適用於iOS的AWS S3 SDK v2 - 將圖像文件下載到UIImage

這裏是我的代碼:

AWSStaticCredentialsProvider *credentialsProvider = [AWSStaticCredentialsProvider credentialsWithAccessKey:@"MY_ACCESS_KEY" secretKey:@"MY_SECRET_KEY"]; 
    AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSWest1 credentialsProvider:credentialsProvider]; 
    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration; 

    AWSS3 *transferManager = [[AWSS3 alloc] initWithConfiguration:configuration]; 
    AWSS3GetObjectRequest *getImageRequest = [AWSS3GetObjectRequest new]; 
    getImageRequest.bucket = @"MY_BUCKET"; 
    getImageRequest.key = @"MY_KEY"; 

    [[transferManager getObject:getImageRequest] continueWithBlock:^id(BFTask *task) { 
     if(task.error) 
     { 
      NSLog(@"Error: %@",task.error); 
     } 
     else 
     { 
      NSLog(@"Got image"); 
      NSData *data = [task.result body]; 
      UIImage *image = [UIImage imageWithData:data]; 
      myImageView.image = image; 
     } 
     return nil; 
    }]; 

當這段代碼執行後,continueWithBlock得到執行,沒有任務的錯誤,所以了圖像記錄。這很快發生。但是,直到大約10秒鐘之後,UIImageView纔會在屏幕上更新。我甚至跑過了調試器,看看NSLog(@"Got image");系列之後的任何行是否花了很長時間,但沒有。它們都執行得非常快,但是UIImageView不會在UI上更新。

回答

5

問題是您正在從後臺線程更新UI組件。 continueWithBlock:塊在後臺線程中執行,並導致上述行爲。你有兩個選擇:

  1. 使用大中央調度中塊和主線程上運行它:

    ... 
    NSURL *fileURL = [task.result body]; 
    NSData *data = // convert fileURL to data 
    dispatch_async(dispatch_get_main_queue(), ^{ 
        UIImage *image = [UIImage imageWithData:data]; 
        myImageView.image = image; 
    }); 
    ... 
    
  2. 使用mainThreadExecutor運行在主線程塊:

    [[transferManager getObject:getImageRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] 
                     withBlock:^id(BFTask *task) { 
    ... 
    

希望這會有所幫助,

+0

謝謝,作品像一個魅力;)總是很高興聽到你正在努力與圖書館的創造者。 –

+0

順便提一下,我注意到它實際上需要幾秒鐘才能下載一個小圖像,但我認爲如果我利用CloudFront將會解決此問題 –

+0

[task.result body]是NSURL的一個實例,而不是NSData。在aws-ios-sdk-2.1.2上測試 – Javan

相關問題