执行下面的代码时,我看到回调执行(通过“success!”验证),但UI activityIndicator上的activityIndicator不会停止旋转。
有时它会在10-20秒后停止,有时会永远运行。回调应该在主线程上运行,所以我不确定是什么导致它延迟/失败。
activityIndicator.startAnimating()
loadData("data") {(success: Bool) in
if success {
// I see this being printed
println("success!")
}
// This isn't updating on the UI! The wheel keeps spinning
self.activityIndicator.stopAnimating()
}
loadData函数正在使用Core Data执行块保存:
public func loadData(completionHandler: (success: Bool) -> Void) {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let appContext = appDelegate.managedObjectContext!
let managedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedContext.persistentStoreCoordinator = appContext.persistentStoreCoordinator
managedContext.performBlock({
//NSManagedObject inserts - working...
if !managedContext.save(&error) {
completionHandler(success: false)
}
completionHandler(success: true)
})
}
非常感谢任何帮助!
答案 0 :(得分:3)
activityIndicator.startAnimating()
loadData("data") {(success: Bool) in
if success {
// I see this being printed
println("success!")
}
dispatch_async(dispatch_get_main_queue()) {
// This isn't updating on the UI! The wheel keeps spinning
self.activityIndicator.stopAnimating()
}
}
此外,我注意到如果出现错误,您将调用完成块两次。所以在第一个完成块之后添加一个返回。像这样:
public func loadData(completionHandler: (success: Bool) -> Void) {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let appContext = appDelegate.managedObjectContext!
let managedContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
managedContext.persistentStoreCoordinator = appContext.persistentStoreCoordinator
managedContext.performBlock({
//NSManagedObject inserts - working...
if !managedContext.save(&error) {
completionHandler(success: false)
return
}
completionHandler(success: true)
})
}
答案 1 :(得分:0)
我有一个类似的问题并通过首先设置活动指示器的动画,然后将剩下的代码放到后台线程,然后在主线程上调用stop动画来解决它。
activityIndicator.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { ()->() in
loadData("data") {(success: Bool) in
if success {
// I see this being printed
println("success!")
}
// This isn't updating on the UI! The wheel keeps spinning
dispatch_async(dispatch_get_main_queue(), {
self.activityIndicator.stopAnimating()
})
}
我没有在这里更新结束括号,假设你有更多因为你正在工作的闭包。