LoginSignup
7
7

More than 5 years have passed since last update.

ローカル通知を毎週決まった曜日にする

Last updated at Posted at 2016-03-07

意外と手こずったのでメモしておきます。

まずは毎週月曜日に通知したいなら月曜日のNSDateオブジェクトを、毎週月曜日に通知したいなら月曜日のNSDateオブジェクトを作らないといけない。そして、NSDateの時刻は通知したい時刻になっている必要がある。

let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.locale = NSLocale.currentLocale()
let comps = NSDateComponents()
comps.year = 2000       // 年度は適当で良い
comps.weekOfMonth = 1   // 適当で良いが、1で良いだろう
comps.weekOfYear = 1    // これも1で良い
comps.weekday = 2       // ここは重要。日曜日が1で月曜日が2、あと曜日が進むごとに+1されていく
comps.hour = self.hour      // 通知したい時刻(時)
comps.minute = self.minute  // 通知したい時刻(分)
// 指定曜日指定時刻のNSDateを得る
let fireDate = cal.dateFromComponents(comps)!

NSLocalNotificationを生成

let notification = UILocalNotification()
notification.fireDate = fireDate    // さっき作った指定曜日が入っているNSDate
notification.repeatInterval = NSCalendarUnit.WeekOfYear  // NSDateの曜日で毎週通知を示す
notification.alertBody = "時間だよ!"
notification.soundName = UILocalNotificationDefaultSoundName

後は登録するだけ

let app = UIApplication.sharedApplication()
app.scheduleLocalNotification(notification)
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7