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

时间:2014-07-23 20:10:28

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

似乎这应该相对简单。我正在使用适用于iOS的AWS SDK(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,没有任务错误,因此记录了得到图像。这种情况发生得相当快。但是,直到大约10秒钟后,UIImageView才会在屏幕上更新。我甚至通过调试器来查看NSLog(@"Got image");行之后的任何行是否需要很长时间,而不是。它们都执行得非常快,但UIImageView不会在UI上更新。

1 个答案:

答案 0 :(得分:5)

问题是您正在从后台线程更新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) {
    ...
    
  3. 希望这有帮助,