Constructing a date for getRequestedUpdateDateWithHandler: - swift

I need to update my watchOS complication at midnight every day.
startOfDay is the beginning of the day (i.e., 12 AM today).
Should I add a day to the start of today like this?
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
let startOfDay = NSDate().startOfDay
let components = NSDateComponents()
components.day = 1
let startOfNextDay = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions())
handler(startOfNextDay)
}
Or should I not add a day to the code, and just do something like this:
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
let startOfDay = NSDate().startOfDay
handler(startOfDay)
}

You'd want to advance the date one day, since you want your next requested update to occur at tomorrow's midnight. The first method would do what you want, but you can simplify it as follows:
let calendar = NSCalendar.currentCalendar()
let startOfDay = calendar.startOfDayForDate(NSDate())
let startOfNextDay = calendar.dateByAddingUnit(.Day, value: 1, toDate: startOfDay, options: NSCalendarOptions())!
The second code would return today's 12 AM, which would already be in the past.

Related

Swift: check if date is the same date as any day in array of dates?

I have an array of date objects - posts. And I am looping through a month. For each day, I want to check if some date in the array is on the same day. So far I have this:
var date = month?.startOfMonth()
var end = month?.endOfMonth()
while date! <= end! {
if posts.reduce(false,{Calendar.current.isDate(date, inSameDayAsDate: post.timeStamp)}) == true {
....
}
date = Calendar.current.date(byAdding: .day, value: 1, to: date!)
}
I believe that this starts with false and for each day in posts it checks whether its in the same day and if it is it turns the result into true. However I think it also changes it back to false the next time it encounters a false value...
What I want is something that returns true if any of the dates in posts is the same as some day rather than the last one. How can I do this?
Your current code is mostly OK though I would replace reduce with contains.
if let start = month?.startOfMonth(), let end = month?.endOfMonth() {
var date = start
var found = false
while !found && date <= end {
if posts.contains { Calendar.current.isDate(date, inSameDayAs: $0.timeStamp) } {
found = true
}
date = Calendar.current.date(byAdding: .day, value: 1, to: date)
}
if found {
// We have a match
}
}
I am basically building a stack view - for every day - I create a rectangle which is blue if there is a post that day and clear if not. Thus I probably do need to know the day. However filtering the array for elements which are in the specified month seems interesting. Can you show how to do that? Perhaps I could specify the location of just those days and then fill the rest of the stackArray with clear values using insertItem atIndex
Basically, I might start with two functions, one to filter the dates by month and one to filter by day. The reason I would so this, in your case, is you for each day, you don't want to refilter all the available dates for the month (but that's just me)
func dates(_ dates: [Date], withinMonth month: Int) -> [Date] {
let calendar = Calendar.current
let components: Set<Calendar.Component> = [.month]
let filtered = dates.filter { (date) -> Bool in
calendar.dateComponents(components, from: date).month == month
}
return filtered
}
func dates(_ dates: [Date], forDay day: Int) -> [Date] {
let calendar = Calendar.current
let components: Set<Calendar.Component> = [.day]
let filtered = dates.filter { (date) -> Bool in
calendar.dateComponents(components, from: date).day == day
}
return filtered
}
You could, use a contains approach, matching both the month and day, but again, there is an overhead to consider. In the above example, you could simply check to see if the day is contained in the resulting filtered dates by month, which might be closer to you desired result
nb This is not as efficient as something like first or contains as this will iterate the entire array finding every matching element, but, it has the nice side effect of providing you with more information. For example, you could sort the resulting filters and simply iterate from the start of the month to the end, popping off each match day as it occurs, as an idea
Thinking out loud...
Another approach might be to filter the available date's by the month, as above, but then to map the result to a Set of days (ie Int), this would allow you to either iterate over each day of the month and use contains(day) to perform a simple check to see if the day is contained or not.
Equally, you could map the view's to each day and iterate of the Set, changing the state of each view.
This all depends on more context then is available, but needless to say, there are any number of ways you might approach this problem
[Updated] As rightly mentioned already, you might be more interested in having a Set of days that have at least one post, something like:
let dayComponents: Set<Calendar.Component> = [.day, .month, .year, .era]
let calendar = Calendar.current
let daysWithPosts = Set(posts.map { post in
calendar.dateComponents(dayComponents, from: post.date)
})
Then for each date you can check if it's in that set (context unchanged, mind the force unwraps):
while date! <= end! {
let currentDayComponents = calendar.dateComponents(dayComponents, from: date)
let postsFound = daysWithPosts.contains(currentDayComponents)
// <use postsFound as needed>
date = Calendar.current.date(byAdding: .day, value: 1, to: date!)
}
Original answer, adapted for multiple dates:
This should tell if there are posts on a given date's day:
func areTherePosts(in posts: [Post], fromSameDayAs date: Date) -> Bool {
let calendar = Calendar.current
let dayComponents: Set<Calendar.Component> = [.day, .month, .year, .era]
let specificDateComponents = calendar.dateComponents(dayComponents, from: date)
return posts.contains { post in
calendar.dateComponents(dayComponents, from: post.date) == specificDateComponents
}
}
Usage in your context (again, unchanged):
while date! <= end! {
let postsFound = areTherePosts(in: posts, fromSameDayAs: date!)
// <use postsFound as needed>
date = Calendar.current.date(byAdding: .day, value: 1, to: date!)
}

Creating UILocalNotifications with CoreData attribute

In my iOS app I am trying to create a localNotification to notify the user 15 minutes prior to the event beginning. However I am stuck. I am using CoreData to store data. I have an Appointment object which can be created. A date attribute is associated with a Appointment object. I am really stuck with it. I do not know how to set up the timeInterval and the rest of the notification process.
I do not know how to set up the timeInterval from the time the Appointment is created to 15 minutes prior to when it begins.
Here is some of my code:
func scheduleNotifications() {
let content = UNMutableNotificationContent()
guard let client = client, let name = client.name, let formula = formula, let date = formula.date else { return }
content.title = "BookMe"
content.subtitle = ""
content.body = "Your appointment with \(name) will begin soon."
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: ??, repeats: false)
Edited: This is what I have but nothing is firing.
let date = formula.date
let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: date as Date)
guard let timeInterval = fireDate?.timeIntervalSince(Date()) else { return }
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
let request = UNNotificationRequest(identifier: self.timerUserNotificationIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
As I understand it you are looking to find a time interval between right now and 15 minutes before some date so that you can fire a notification 15 minutes before that date.
Here's a quick example I knocked up in a playground
// Create a date in the future - this is what you get from your own data object and I'm creating it here just so I have a date.
let scheduledDate = Calendar.current.date(from: DateComponents(year: 2017, month: 09, day: 22, hour: 22))!
// Create a date 15 minutes earlier than your shcheduled date, this is when you want your notification to fire
let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: scheduledDate)!
// Then just work out the time interval between the fire date and now to get the time interval
let timeInterval = fireDate.timeIntervalSince(Date())
Excuse the force unwrapping of the created dates, these are because it's an example, you should instead not use exclamation marks and handle errors gracefully.
edited to add
UNTimeIntervalNotificationTrigger, which you are trying to use requires a TimeInterval between now and the time you want to fire the notification. A TimeInterval is a Double that represents a number of seconds. In some cases, such as this one, it represents a delay, the number of seconds between now and the time you want to fire the the notification. In other cases it represents a date by the number of seconds from a fixed date. This fixed date is either timeIntervalSince1970 - "The interval between the date object and 00:00:00 UTC on 1 January 1970." Which is what you use for UNIX timestamps or timeIntervalSinceReferenceDate - "The interval between the date object and 00:00:00 UTC on 1 January 2001."
Whatever you do, resist the temptation to modify dates by adding or removing numbers of seconds directly, use DateComponents instead.

NSDate: Getting values for Tomorrow or Yesterday

I have a piece of code that basically acts in 2 parts:
Part 1: The user sets a Date with a UIDatePicker. For example, the user selects 1 day ahead from the current date. So the selected new date is 5/19/16 instead of 5/18/16.
Part 1 code
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
var dateString = "May-19-2016"
dateFormatter.dateFormat = "MMMM-dd-yyyy"
var due_date = dateFormatter.dateFromString(dateString)!
Part 2: I have created code that counts how many days are left from the selected date to the current date. In this example, somehow my code is saying its 0 days before tomorrow. Here is the code for the second part:
Second Part:
func computeDates(dueDate:NSDate)-> Int {
let currentDate = NSDate()
// Adding days to currentDate
let daysToAdd = 1
// Adding on Unit to the current instance
let calculateDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Day, value: daysToAdd, toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0))
// Figure out many days from may 3rd
let cal = NSCalendar.currentCalendar()
let unit = NSCalendarUnit.Day
let components = cal.components(unit, fromDate: currentDate, toDate: dueDate, options: [])
let countLeft = components.day
return countLeft
}
print("Days left: \(computeDates(due_date)) ")
// Tests
let calc_date = computeDates(due_date)
if calc_date <= -1 {
print("Yesterday")
} else if calc_date == 0 {
print("Today")
} else if calc_date > 1 {
print("Tomorrow")
}
In the part 1 example, I used a static date which I use to test this code. In this part, I set May 19, 2016, one day ahead. In the second part below in the if statement, It somehow says I have 0 days left and from what i am trying to do, it's suppose to say 1 day left before tomorrow the 19th.
Another example, If i change the 19th to the 20th, I want it to say "In 2 days" from now.
Now if I revert the day to lets say, the 15th of may (in the past), Then the if statement would say something like Overdue or the past.
How can I solve this?
It would help if you thought of NSDate as a structure that operates with the number of seconds from 2001. It means if you pick a "date", it contains "date and time". All you need to do to calculate the correct number of days between specific "dates" is to truncate a time component.
But if you only need to check whether the provided date is Yesterday, Today, or Tomorrow, NSCalendar has methods for this purpose:
Objective-C:
- (BOOL)isDateInToday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
- (BOOL)isDateInYesterday:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
- (BOOL)isDateInTomorrow:(NSDate *)date NS_AVAILABLE(10_9, 8_0);
And Swift:
#available(OSX 10.9, *)
public func isDateInYesterday(date: NSDate) -> Bool
#available(OSX 10.9, *)
public func isDateInTomorrow(date: NSDate) -> Bool
#available(OSX 10.9, *)
public func isDateInWeekend(date: NSDate) -> Bool

How do I filter events created for the current date in the Realm swift?

How do I filter events created for the current date in the Realm swift?
I tried something like below but this wrong.
let dtSource = datasource.filter("Create == NSDate()").count
Update: Getting the filter creating my date as a string.
http://i.stack.imgur.com/8fLX9.png
http://i.stack.imgur.com/HDR2X.png
A query in the form of Create == NSDate() will check exact date equality, which will compare down to the second. If you want to check if a date is between a given interval, like checking if it's on a specific day, regardless of the time of day, you could do a BETWEEN check:
let dtSource = datasource.filter("Create BETWEEN %#", [firstDate, secondDate]).count
Update:
Here's a full code sample to get all date models for the current day:
import RealmSwift
class Event: Object {
dynamic var date = NSDate()
}
let todayStart = Calendar.current.startOfDay(for: Date())
let todayEnd: Date = {
let components = DateComponents(day: 1, second: -1)
return Calendar.current.date(byAdding: components, to: todayStart)!
}()
events = realm.objects(Event.self).filter("date BETWEEN %#", [todayStart, todayEnd])

add a new row in tableView every single month

i have a date say 2 March 2016 stored as NSUserDefaults and i want to add a new row in TableView every time a new Month is about to come , so what should i do for accomplishing this , IMO comparing the stored Date and Current Date and if
in Curent Date a new Month is about to come in next 7 days then add the
row into table but i don't know where to start, anyone can give me some hint for checking current date's next 7 days for if a new months is about to come
and if my approach is not good enough then please correct me it'll be so appreciated by me and helpful for me
please see example for better understanding :
storedDate = 2 March 2016
currentDate = 26 March 2016
if CurrentDate + 1 Week == newMonth {
//add the Row into TableView
}
You can add an Extension to NSDate and then do all sorts of day/month addition
This method you can use to add 7 days to the current date...
func dateByAddingDays(daysToAdd: Int)-> NSDate {
let dateComponents = NSDateComponents()
dateComponents.day = daysToAdd
let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
return newDate!
}
This method to add months to current date
func dateByAddingMonths(monthsToAdd: Int)-> NSDate {
let dateComponents = NSDateComponents()
dateComponents.month = monthsToAdd
let newDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: self, options: .MatchFirst)
return newDate!
}
Then you need to check that date you created and see if it its a different month than the one that is stored..
func compareMonths(newDate:NSDate)-> Bool {
let today = NSDate()
let todayPlusSeven = today.dateByAddingDays(7)
return todayPlusSeven.isNextMonth(storedDate)
}
Using this method to check if the months of 2 dates are the same
func isNextMonth(storedDate: NSDate)-> Bool {
return isSameMonthAsDate(storedDate.dateByAddingMonth(1))
}
func isSameMonthAsDate(compareDate: NSDate)-> Bool {
let comp1 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: self)
let comp2 = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: compareDate)
return ((comp1.month == comp2.month) && (comp1.year == comp2.year))
}
An oldie but still goodie, is this page of Date helpers from Erica Sadun's github page here They are all in Obj-c but can be converted to swift easily enough. I still reference it when i need help doing date math