【问题标题】:AWS S3 SDK v2 for iOS - Download an image file to UIImage适用于 iOS 的 AWS S3 SDK v2 - 将图像文件下载到 UIImage
【发布时间】:2016-01-12 09:17:57
【问题描述】:

看来这应该比较简单。我正在使用适用于 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 被执行,没有任务错误,所以 Got image 被记录下来。这发生得相当快。然而,直到大约 10 秒后 UIImageView 才在屏幕上更新。我什至通过调试器来查看NSLog(@"Got image"); 行之后的任何行是否花费了很长时间,而事实并非如此。它们都执行得非常快,但是 UIImageView 不会在 UI 上更新。

【问题讨论】:

    标签: ios amazon-web-services amazon-s3


    【解决方案1】:

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

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

    希望这会有所帮助,

    【讨论】:

    • 谢谢你,工作就像一个魅力;)总是很高兴听到你正在努力的图书馆的创建者。
    • 顺便说一句,现在我注意到下载一个小图像实际上需要几秒钟,但我认为如果我利用 CloudFront 将会解决这个问题
    • [task.result body] 是 NSURL 的一个实例,而不是 NSData。在 aws-ios-sdk-2.1.2 上测试
    猜你喜欢
    • 2014-10-11
    • 2015-04-18
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2014-09-11
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多