2015-09-26 107 views
1

我正在製作iPhone應用程序並使用S3存儲圖像,現在我想下載它們並將它們顯示在我的應用程序中。問題是我在顯示圖像之前執行AWSS3TransferManagerDownloadRequest。問題在於:第一次我想要顯示圖像時,它不會顯示,大概是因爲下載請求尚未完成。之後,每當我重新運行我的項目時,圖像顯示正常,大概是因爲它已經存儲在本地。那麼我怎樣才能讓圖像馬上顯示出來。這是相關的功能。等待AWSS3TransferManagerDownloadRequest完成(iOS,Objective-C)

- (void)makeImageWithBucket:(NSString *)bucket withKey:(NSString *)key atLocation:(NSString *)location{ 
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager]; 

// Construct the NSURL for the download location. 
NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:location]; 
NSURL *downloadingFileURL = [NSURL fileURLWithPath:downloadingFilePath]; 

// Construct the download request. 
AWSS3TransferManagerDownloadRequest *downloadRequest = [AWSS3TransferManagerDownloadRequest new]; 

downloadRequest.bucket = bucket; 
downloadRequest.key = key; 
downloadRequest.downloadingFileURL = downloadingFileURL; 

// Download the file. 
[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] 
                 withBlock:^id(AWSTask *task) { 
                  if (task.error){ 
                   if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) { 
                    switch (task.error.code) { 
                     case AWSS3TransferManagerErrorCancelled: 
                     case AWSS3TransferManagerErrorPaused: 
                      break; 

                     default: 
                      NSLog(@"Error: %@", task.error); 
                      break; 
                    } 
                   } else { 
                    // Unknown error. 
                    NSLog(@"Error: %@", task.error); 
                   } 
                  } 

                  if (task.result) { 

                   AWSS3TransferManagerDownloadOutput *downloadOutput = task.result; 

                   //File downloaded successfully. 
                  } 
                  return nil; 
                 }]; 

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)]; 
imageView.image = [UIImage imageWithContentsOfFile:downloadingFilePath]; 
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame: self.view.frame]; 
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
scrollView.contentSize = CGSizeMake(375,imageView.frame.size.height); 
[scrollView addSubview:imageView]; 
[self.view addSubview:scrollView];} 

回答

1

您可以從'continue with'塊更新UI。所以,如果你正在顯示圖像是nil,您可以在您的代碼段的這部分更新:

if (task.result) { 
    AWSS3TransferManagerDownloadOutput *downloadOutput = task.result; 

    //File downloaded successfully. 
    //Display the downloaded image here. 
} 
+0

你好洋介,這個建議是好的,但現在還有另一個問題。整個方法現在在下載完成之前完成,這導致主功能中的其他代碼在S3完成下載之前運行。我能做些什麼來確保該方法在下載之前沒有完成? –

+0

這聽起來像你設計你的應用程序主要利用同步功能。 iOS應用程序的許多方面都是事件驅動的(例如,用戶點擊下載按鈕,應用程序下載對象)並且是異步的。我建議你重新設計你的「主要功能」,從同步到異步,以便它在得到響應時處理響應。網上有很多資源用於設計異步API。 –