异步下载图像而不阻止UI

时间:2014-05-12 14:52:57

标签: ios multithreading

我需要异步下载图像,而不会阻止iOS应用中的UI。下载image时,“等待”UIView必须至少显示3秒钟。我想实现一个不阻止UI管理的解决方案(即使在当前实现中,在图像下载过程中也没有提供用户操作)。

目前的解决方案是:

- main thread: dispatch_async + block to download the image (described in thread_2);
- main thread: sleep for three seconds;
- main thread: P (wait) on a semaphore S;
- main thread: read data or error message set by thread_2, then behave accordingly.


- thread_2: download the image, set data or error flag/msg according to the download result;
- thread_2: V (signal) on the semaphore S.

还有其他解决方案,例如基于NSNotification,但这个解决方案似乎最适合3秒延迟。

我的问题是:当主线程处于休眠状态时(或等待信号量时),UI是否被冻结?如果是,哪种解决方案最好?

您如何看待第二个:

- main thread: dispatch_async + block to download the image (described in thread_2);
- main thread: dispath_async thread_3

- thread_2: as above

- thread_3: sleep three seconds, P on semaphore S;
- thread_3: read data or error message set by thread_2, prepare everything, then behave accordingly using the main_queue.

2 个答案:

答案 0 :(得分:2)

这是一种使用多线程并具有特定延迟的方法

    double delayInSeconds =3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

    //Entering a specific thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{

        //Wait delayInSeconds and this thread will dispatch
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //Do your main thread operations here

        });
    });

答案 1 :(得分:0)

或多或少你可以这样做:

dispatch_async(your_download_queue, ^{
         dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);
         //download image

         dispatch_after(timer, dispatch_get_main_queue(), ^{

                 //update ui with your image
         }); 
});