2015-04-01 73 views
2

當執行下面的代碼時,我會看到回調execute(通過「success!」驗證),但UI activityIndi​​cator上的activityIndi​​cator不會停止旋轉。回調中的Swift UI更新有時不會執行

有時它會在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函數保存使用核心數據執行塊:

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

「應該在主線程中運行。」 - 你用調試器確認是這種情況? – nhgrif 2015-04-01 20:53:00

+0

@nhgrif可能是對的。所有UI代碼都應該在主線程上執行。 – 2015-04-01 21:01:08

+0

是的@nhgrif,你是對的......我的錯誤假設。我做了下面的更新Christos Hadjikyriacou建議,現在一切正常。謝謝您的幫助! – StCleezy 2015-04-02 02:28:54

回答

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) 
}) 

}

+0

這個伎倆!謝謝!並感謝最終的回報。 – StCleezy 2015-04-02 02:26:27

+0

你可以只''completionHandler(成功:managedContext.save(&錯誤))'擺脫'if'和'return'。 – nhgrif 2015-04-02 02:30:53

0

我也有類似的問題,並通過第一動畫的活動的指標,然後將代碼的其餘部分下降到一個後臺線程,則主線程調用停止動畫解決它。

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() 
}) 
} 

我這裏沒有更新右括號假設你有更多的,因爲你在工作的封閉