适用于iOS的AWS S3 SDK v2 – 将图像文件下载到UIImage

看来这应该是比较简单的。 我正在使用适用于iOS的AWS开发工具包(v2),我试图下载一个.png文件并将其显示在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被执行,没有任何错误,所以得到的图像被logging下来。 这很快发生。 但是,直到大约10秒钟之后,UIImageView才会在屏幕上更新。 我甚至跑过debugging器,看看NSLog(@"Got image");后面是否有行NSLog(@"Got image"); 行了很长时间,他们没有。 他们都执行得非常快,但UIImageView不会在UI上更新。

问题是您正在从后台线程更新UI组件。 continueWithBlock:块在后台线程中执行,并导致上述行为。 你有两个select:

  1. 在块中使用Grand Central Dispatch并在主线程上运行它:

     ... 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) { ... 

希望这可以帮助,