AWS S3 SDK V2的iOS - 下载一个图像文件的UIImage图像文件、SDK、AWS、UIImage

2023-09-11 09:59:06 作者:孤

看来这应该是比较简单的。我使用AWS SDK(V2)用于iOS和我试图下载一个PNG文件,并将其显示在一个UIImage屏幕。一切实际工作!只是很奇怪......

Seems this should be relatively simple. I'm using the AWS SDK (v2) for iOS and I'm trying to download a .png file and display it to the screen in a UIImage. Everything actually works! Just very strangely...

下面是我的code:

    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;
    }];

在此code被执行时,continueWithBlock得到执行,没有任务的错误,所以得到了图片登录。而这种情况相当迅速。但是,这不是直到大约10秒钟后屏幕上的UIImageView的更新。我甚至通过调试运行,看看下面的任何行的的NSLog(@得到的图像); 行正在采取长,他们不是。他们都执行得很快,但随后的的UIImageView将不会被更新的用户界面。

When this code gets executed, the continueWithBlock gets executed, there is no task error, so Got image is logged. And this happens fairly quickly. However, it's not until about 10 seconds later that the UIImageView updates on the screen. I even ran through the debugger to see if any of the lines following the NSLog(@"Got image"); line were taking long and they weren't. They were all executing very quickly but then the UIImageView would not be updated on the UI.

推荐答案

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

The issue is that you are updating UI component from a background thread. The continueWithBlock: block is executed in the background thread, and it is causing the aforementioned behavior. You have two options:

使用大中央调度中块和主线程上运行它:

Use Grand Central Dispatch in the block and run it on the main thread:

...
NSData *data = [task.result body];
dispatch_async(dispatch_get_main_queue(), ^{
    UIImage *image = [UIImage imageWithData:data];
    myImageView.image = image;
});
...

手机app地图定位UI图标PSD素材免费下载 红动网

使用 mainThreadExecutor 运行在主线程块:

Use mainThreadExecutor to run the block on the main thread:

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

希望这有助于