ErkanA
ErkanA

Reputation: 179

NSDate from week number

I am trying to create a weekly recurring local notification using Swift. Notification is going to be set to first day of every week, and in 10:00. Ofcourse I don't want to set a notification for a past date, so I need to see if now it has passed first day of week 10:00. If not, I will create notification for today 10:00, else next week monday 10:00.

I created an extension to calculate week number for current date.

    extension NSDate {

        func weekOfYear() -> Int {
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(NSCalendarUnit.WeekOfYear, fromDate: self)
        let weekOfYear = components.weekOfYear

        return weekOfYear
        }
    }

I couldn't go any further than this. Any help is appreciated. Regards.

Upvotes: 1

Views: 329

Answers (1)

Martin R
Martin R

Reputation: 540075

There is an easier solution to your problem. You can use the nextDateAfterDate() method of NSCalendar:

let cal = NSCalendar.currentCalendar()
let comps = NSDateComponents()
comps.hour = 10
comps.weekday = cal.firstWeekday

let now = NSDate()
let fireDate = cal.nextDateAfterDate(now, matchingComponents: comps, options: [.MatchNextTimePreservingSmallerUnits])!

This gives the first date in the future which is at 10:00 on the first day of the week.

Upvotes: 2

Related Questions