0

Generally speaking I want to query my DB for all new FeedItems in the last 10 minutes. This Feed should have a nice batch of new FeedItems every 10 minutes.

I've written a function:

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

This function works to update the Badge Notification however when I set a timer for it to run every ten minutes:

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

It does work, but I get the following warning which I know to be a serious one:

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

Given the following parameters:

  1. If user is on Tab1 where the FeedItems, the query runs and the badge is populated, I want the Badge to show up and then disappear when the user reloads the feed via UIRefreshControl()

  2. If user is on Tab2 or another View, I want the Badge to show up and only disappear when user presses Tab1.

  3. I want the query for the amount of new items to run every 10 minutes.

I've tried running getRecentFeedItems() in viewWillAppear as well as viewDidAppear().

Is there a better way to do this?

SamYoungNY
  • 6,444
  • 6
  • 26
  • 43

1 Answers1

0

As far as I can tell the only thing you'll need to change is to run getRecentFeedItems in the background and only update the badge value after you get a success or failure message from the query. This will prevent the warning of an operation occurring on the main thread.

Hope this helps!

Studio Symposium
  • 287
  • 2
  • 16
  • Thanks for your response but I have two questions... Where in the ViewController file should I be creating and placing this background process, and what do you mean by 'update the badge after you get a success or failure msg'... I thought that the success is implied inherently by the `if newBadgeCount > 0 ` statement. Do you mean I should be doing something more like `if error == nil {...}` ? – SamYoungNY Oct 15 '15 at 15:22
  • Yes, check to see if there's actually an error message and update after a success comes back. Then run a check if `newBadgeCount > 0` in the success block. – Studio Symposium Oct 15 '15 at 19:08