Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Every Day in swift syntax

Tags:

ios

swift

Working on a quote app, and as a beginner I decided to rule out using CoreData and Sqlite in my app. Therefore I decided to try a collection and change the text label.I have a collection stored in an array. I'm trying to achieve the text changing every 24 hours and it changes at 8:00 A.M E.S.T (so 8 A.M to 8 A.M)I would like the outline to be something like

quoteindex = 0
if(time_elasped:24 hours something about 8:00 A.M EST) {
quote.text = quoteCollection.quoteArray[quoteIndex]
quoteindex++ (next quote in array)
}

How would I organize something like this in terms of syntax? Would I use another loop?

like image 321
Henry Li Avatar asked Nov 28 '25 10:11

Henry Li


1 Answers

An easy way to do this would be to use NSUserDefaults to store an NSDictionary containing the last time and index when the user last retrieved a quote.

in viewDidLoad: (or make into standalone function - checkLastRetrieval())

let userDefaults = NSUserDefaults.standardUserDefaults()

if let lastRetrieval = userDefaults.dictionaryForKey("lastRetrieval") {
    if let lastDate = lastRetrieval["date"] as? NSDate {
        if let index = lastRetrieval["index"] as? Int {
           if abs(lastDate.timeIntervalSinceNow) > 86400 { // seconds in 24 hours
            // Time to change the label
            var nextIndex = index + 1

            // Check to see if next incremented index is out of bounds
            if self.myQuoteArray.count <= nextIndex {
                // Move index back to zero? Behavior up to you...
                nextIndex = 0
            }

            self.myLabel.text = self.myQuoteArray[nextIndex]

            let lastRetrieval : [NSObject : AnyObject] = [
               "date" : NSDate(),
               "index" : nextIndex
             ]

             userDefaults.setObject(lastRetrieval, forKey: "lastRetrieval")
             userDefaults.synchronize()
        }
        // Do nothing, not enough time has elapsed to change labels
      }
   }
} else {

  // No dictionary found, show first quote
  self.myLabel.text = self.myQuoteArray.first!

  // Make new dictionary and save to NSUserDefaults
  let lastRetrieval : [NSObject : AnyObject] = [
    "date" : NSDate(),
    "index" : 0
  ]

  userDefaults.setObject(lastRetrieval, forKey: "lastRetrieval")
  userDefaults.synchronize()
}

You can be more specific using NSDate if you want to ensure a specific time (like 8AM) or make sure that there is a unique quote for every actual day (Monday, Tuesday, etc). This example simply changes the label if the user has seen a quote more than 24 hours ago.

Check out the docs for NSUserDefaults.

EDIT: If you wanted to notify the user at 8AM the next day of a new quote you could send a local notification to the user.

let notification = UILocalNotification()

notification.fireDate = NSDate(timeIntervalSinceNow: someTimeInterval)
notification.timeZone = NSCalender.currentCalendar().timeZone

notification.alertBody = "Some quote" // or "Check the app"
notiication.hasAction = true
notification.alertAction = "View"

application.scheduleLocalNotification(notification)

You would have to calculate the timeInterval to be whatever time is left to 8AM the next day. Check this answer out: https://stackoverflow.com/a/15262058/2881524 (It's objective-c but you should be able to figure it out)

EDIT

To execute code when your view enters the foreground you need to post a notification in your AppDelegate's applicationWillEnterForeground method. And add an observer for that notification in your view controller.

in AppDelegate

let notification = NSNotification(name: "CheckLastQuoteRetrieval", object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)

in ViewController

 override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("checkLastRetrieval"), name: "CheckLastQuoteRetrieval", object: nil)
    checkLastRetrieval()

}
like image 151
gmat1014 Avatar answered Nov 30 '25 00:11

gmat1014



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!