UIActivityIndi​​catorView在dispatch_sync模式下不起作用

时间:2016-04-13 09:22:37

标签: ios swift grand-central-dispatch uiactivityindicatorview

我在我的项目中使用UIActivityIndicatorView,但它不起作用,以下是我的代码:

let globalQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

    dispatch_sync(globalQueueDefault){

        self.activityIndicatorView.hidden = false
        self.activityIndicatorView.startAnimating()

            self.connect()

            sleep(6)
            dispatch_sync(globalQueueDefault) { () -> Void in

                self.activityIndicatorView.stopAnimating()
                self.activityIndicatorView.hidden = true                                             
            }
    }

我已尝试dispatch_syncdispatch_async ...但它不起作用。

2 个答案:

答案 0 :(得分:3)

使用此队列时,您要求代码在后台运行,UI代码只应在主线程上运行。

中包装activityView
dispatch_async(dispatch_get_main_queue(), {() -> Void in

 })

将该代码放回主线程,并按预期工作。

修改后的代码应该类似于

让globalQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

dispatch_async(dispatch_get_main_queue(), {() -> Void in

    self.activityIndicatorView.hidden = false
    self.activityIndicatorView.startAnimating()

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] () -> Void in
         self?.connect()

          sleep(6)

    })

    dispatch_async(dispatch_get_main_queue(), {() -> Void in

         self.activityIndicatorView.stopAnimating()
         self.activityIndicatorView.hidden = true                                             
     }
}

答案 1 :(得分:0)

UIKit通常从主线程处理。因此,每当您尝试更新UI时,都必须将UI相关代码放在主线程中,如下所示。

    dispatch_async(dispatch_get_main_queue(), ^{
         // All UI related code goes here...
         // I am adding few part of your code here.. Please update this according to your requirement.
         self.activityIndicatorView.stopAnimating()
         self.activityIndicatorView.hidden = true 
        });