目的
通常のpush通知(サイレントpush通知ではないもの)を設定しようとしたら、
サイレントpush通知の設定とごっちゃになって、中々苦労した。
この記事は通常のpush通知とサイレントpush通知の設定の比較した記事。
環境
- Xcode Version 13.2.1
- Swift 5
サイレントpush通知とは
iOS7から設定できるようになったpush通知。
利用者に通知を行わず、バックグラウンドでアプリ内処理を行える機能を有する。
通常のpush通知の設定
TARGETSのSigning & CapabilitiesよりPush Notifications
を追加する。
これをやらないとDeviceTokenが取得できない。

AppDelegateにDelegate設定を行う
import UserNotifications
...
class AppDelegate:... UNUserNotificationCenterDelegate {
以下でDeviceTokenを取得
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenComponents = deviceToken.map { data in String(format: "%02.2hhx", data) }
let deviceTokenString = tokenComponents.joined()
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Remote notification support is unavailable due to error: \(error.localizedDescription)")
}
AppDelegateにDelegate関数を設定する
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//code
ompletionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//code
completionHandler([.badge, .sound])
}
サイレントpush通知
TARGETSのSigning & CapabilitiesよりPush Notifications
を追加するのは同じ。
さらにBackground Modes
を追加してRemote notifications
にチェックを入れる。

Delegate設定やToken受信設定は変わらず。
その代わり、AppDelegateに設定するDelegate関数は以下となる。
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//code
completionHandler(.newData)
}
あとpayloadに以下の設定が必要。
"content-available": 1
サイレントpush通知は、通知を受け取った瞬間にdidReceiveRemoteNotification
が呼ばれる。
以上。
push通知については他にも記事あるので、御覧ください。