Reputation: 15
I have a Swift data file in the "Quote a Day" project with 500 quotes and I would like to call updateQuote()
every time it becomes a new day.
The quote string variable updates a UILabel in the QuoteViewcontroller
and the string for the alertBody in UILocalNotifiication()
.
See below for reference:
var quotes:[Quote] = quoteData
var quote: String!
var counter = 0
func updateQuote() {
if counter == quotes.count {
counter = 0
} else {
quote = quotes[counter].quoteTitle
counter++
}
}
I was trying to do something like this with NSDate()
:
let userCalendar = NSCalendar.currentCalendar()
let dayCalendarUnit: NSCalendarUnit = [.Day]
let DayDifference = userCalendar.components(
dayCalendarUnit,
fromDate: lastDate,
toDate: nowDate,
options: [])
var difference = DayDifference.day
if difference > 0 {
updateQuote()
lastDate = nowDate
}
But that logic does not seem to work as I am not sure how to populate lastDate and nowDate on the initial run.
I also I am not sure where to put the above function so that it can keep checking while the app is running in the background.
Any insight would be great.
Upvotes: 0
Views: 817
Reputation: 33979
If you just want the app to show a different quote in a UILabel each day, then the obvious solution is to convert today's date into an integer and then index into your array using that integer. Something like this would do it...
let daysSince1970 = NSDate().timeIntervalSince1970 / 60 / 60 / 24
let index = Int(daysSince1970) % quotes.count
myLabel.text = quotes[index]
The above code doesn't have to run constantly, it only has to run when the app is moved to the foreground.
To put the quote of the day in a notification... Somewhere in your UI you should be asking the user what time they want the quote delivered. Once you have that time, load up several one shot notifications each with a different quote in it and set to deliver on different days (choose the quote with the same algorithm as above, except advance the index once for each day.) I think Apple allows you to load 64 notifications this way.
Upvotes: 1