2015-10-14 54 views
0

一般來說,我想在最近10分鐘內查詢我的數據庫中所有新的FeedItems。該Feed應該每10分鐘有一批新的FeedItem。在選項卡欄中實現iOS徽章通知的最佳方式

我寫了一個函數:

func getRecentFeedItems() { 
    // Set up timing 
    let date = NSDate() 
    let calendar = NSCalendar.autoupdatingCurrentCalendar() 
    let dateMinusTenMin = calendar.dateByAddingUnit(.Minute, value: -10, toDate: date, options: []) 
    //Query the DB 
    let getRecentFeedItems = FeedItem.query() 
    getRecentFeedItems!.whereKey("createdAt", greaterThan: dateMinusTenMin!) 
    let newBadgeCount: Int = (getRecentFeedItems?.countObjects())! 
    if newBadgeCount > 0 { 
     self.navigationController?.tabBarItem.badgeValue = String(newBadgeCount) //update the Badge with the new count 
     print("update the badge with \(newBadgeCount)") 
    } else { 
     self.navigationController?.tabBarItem.badgeValue = nil 
    } 
} 

此功能但是更新徽章通知時,我設置一個計時器,它每10分鐘運行一次:

var updateBadgeQueryTimer = NSTimer.scheduledTimerWithTimeInterval(600.0, target: self, selector: Selector("updateBadgeQuery"), userInfo: nil, repeats: true) 

它的工作,但我得到以下警告,我知道這是一個嚴重的警告:

Warning: A long-running operation is being executed on the main thread. 

鑑於以下荷蘭國際集團的參數:

  1. 如果用戶是在TAB1在FeedItems,查詢運行和徽章被填充,我想要的徽章露面,然後消失,當用戶重新加載通過UIRefreshControl()

  2. 飼料

    如果用戶在Tab2或其他視圖上,我希望徽章出現並且只有在用戶按下Tab1時纔會消失。

  3. 我想要查詢每10分鐘運行的新項目的數量。

我試着在viewWillAppear以及viewDidAppear()中運行getRecentFeedItems()。

有沒有更好的方法來做到這一點?

回答

0

據我所知,您需要更改的唯一方法是在後臺運行getRecentFeedItems,並且只有在您收到查詢中的成功或失敗消息後才更新徽章值。這將防止在主線程上發生操作的警告。

希望這會有所幫助!

+0

感謝您的回覆,但我有兩個問題......我應該在ViewController文件的哪個位置創建並放置此後臺進程,以及「獲取成功或失敗消息後更新徽章」是什麼意思。 ..我認爲,如果newBadgeCount> 0聲明,這個成功就是內在的。你的意思是我應該做更像'if error == nil {...}'的東西嗎? – SamYoungNY

+0

是的,請檢查是否有實際的錯誤消息,並在成功回來後更新。然後在成功塊中檢查'newBadgeCount> 0'。 –

相關問題