带有 NsurlConnection 的 UIViewActivityIndi​​cator 在 swift 中不会停止动画

UIViewActivityIndicator with NsurlConnection does not stop animation in swift

我在单击按钮时调用 callDailyQuotes 方法。 activityIndicator 在从服务器下载数据时开始动画,但随后 activityIndicator 停止动画。

相关代码如下:

self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
self.activityIndicator.startAnimating()
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
   self.callDailyQuotes()
   dispatch_async(dispatch_get_main_queue(), { () -> Void in     
            })
        })

func callDailyQuotes(){
//calling nsurlconnection synchronously
 self.activityIndicator.stopAnimating()
}

发生了什么使 activityIndicator 停止动画?

你必须在主线程中执行 self.activityIndicator.stopAnimating() 调用,所以我的建议是将它移动到你已经添加但留空的 dispatch_async 中:

self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        self.activityIndicator.startAnimating()
        let qualityOfServiceClass = QOS_CLASS_BACKGROUND
        let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
        dispatch_async(backgroundQueue, {
            self.callDailyQuotes()
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.activityIndicator.stopAnimating()
            })
        })

func callDailyQuotes(){
//calling nsurlconnection synchronously
}