2014-12-05 37 views
0

我花了一個星期的時間試圖找出如何做到這一點。等待子視圖顯示,然後處理,然後刪除子視圖

我想要做的是顯示子視圖,然後做我的http調用到後端,然後刪除子視圖。

... 
//Display view 
[superView addSubview:blurredOverlay]; 
[superView bringSubviewToFront:blurredOverlay]; 

//After blurredOverlay is displayed, Try to login the user 
dispatch_group_t d_group = dispatch_group_create(); 
dispatch_queue_t bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
dispatch_group_async(d_group, bg_queue, ^{ 
    //Try to login user 
    success = [self loginUser]; 
    NSLog(@"Success=%i", success); 
    [NSThread sleepForTimeInterval:10.0]; //here to force thread to not return immediatly 
}); 
dispatch_group_wait(d_group, DISPATCH_TIME_FOREVER); 

//Remove the view after the thread is done processing 
[blurredOverlay removeFromSuperview]; 

這是行不通的。如果我有

[blurredOverlay removeFromSuperview]; 

取消註釋,blurOverlay從不顯示。如果我將它評論出來,會顯示blurredOvleray,但我顯然無法刪除它。

我需要的是首先顯示blurredOverlay,然後嘗試登錄用戶(顯示blurredOverlay時),並在loginUser返回後,移除模糊的顯示。

+0

我已經嘗試了多種不同的dispatch_group_async變體,但我是新的線程,沒有任何我幫助過。 – lr100 2014-12-05 22:41:23

+0

而不是使用dispatch_groups,使用NSURLSession或NSURLConnection的sendAsynchronousRequest,並在完成塊中刪除覆蓋。 – rdelmar 2014-12-05 22:42:56

回答

1

您正在將此塊調度到異步隊列。您的主線程不會停下來等到該塊完成。 但你已經知道了。這就是爲什麼你使用dispatch組來阻塞主線程直到後臺任務完成。
該方法的問題在於僅在runloop完成當前迭代後刷新UI。直到你的方法離開後,這種情況纔會發生。

這是當你的代碼運行時會發生什麼:

  • UI是由系統更新
  • 輸入的方法
    • 塊添加視圖
    • 調度塊
    • 等待到完成
    • 刪除視圖
  • 離開你的方法
  • UI是由系統

更新你看這個問題?在添加視圖和刪除視圖之間UI不會更新。

這是你應該做的。您添加視圖。用你的任務發送塊,使其在後臺運行。在該背景塊的末尾,您將分派另一個塊,當您的後臺任務完成時將運行該塊。該塊在主線程上運行並刪除您的視圖。

[superView addSubview:blurredOverlay]; 
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
dispatch_async(backgroundQueue, ^{ 

    // run your web request here 
    [NSThread sleepForTimeInterval:10.0]; 

    // task is done 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // UI updates have to run on the main thread, so dispatch the removal 
     [blurredOverlay removeFromSuperview]; 
    }); 
}); 
+0

我可以發誓我也試過這個。一定沒有,因爲它工作!現在唯一的事情是我的Web請求中有AlertViews。它會返回,擺脫blurredOverlay,但等待,直到下一個runloop週期顯示警報。我需要的是在blurOverlay被移除之前顯示警報。生病了吧。非常感謝! – lr100 2014-12-05 22:56:07

相關問題