LoginSignup
1
4

More than 3 years have passed since last update.

【Swift 】通知を出す方法について

Posted at

通知を許可しているか確認

通知を出す場合、事前に通知を許可しているか確認する必要があります。

// 通知許可の取得
UNUserNotificationCenter.current().requestAuthorization(
     options: [.alert, .sound, .badge]){
     (granted, _) in
     if granted{
          UNUserNotificationCenter.current().delegate = self
     }
}

指定時間経過で通知を出す

○秒後に実行させる場合、UNTimeIntervalNotificationTrigger(timeInterval: , repeats:)で通知を作成させる必要があります。

let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.title = "タイトル"
content.subtitle = "サブタイトル"
content.body = "内容"

// 指定時間後に実行
let timer = 10

// 通知リクエストを作成
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timer), repeats: false)
let identifier = NSUUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

// 通知リクエストを登録
UNUserNotificationCenter.current().add(request){ (error : Error?) in
     if let error = error {
          print(error.localizedDescription)
     }
}

指定時刻になったときに通知を出す

指定時刻に実行させる場合、UNCalendarNotificationTrigger(dateMatching: , repeats:)で通知を作成させる必要があります。

let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.title = "タイトル"
content.subtitle = "サブタイトル"
content.body = "内容"

// 通知時刻を指定
let date = Date()
let newDate = Date(timeInterval: 60, since: date)
let component = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: newDate)

// リクエストを作成
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
let identifier = NSUUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

// 通知リクエストを登録
UNUserNotificationCenter.current().add(request){ (error : Error?) in
     if let error = error {
          print(error.localizedDescription)
     }
}
1
4
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
1
4