Xcode 10 Swift 4.2
アプリがフォアグラウンドにあるときにプッシュ通知を表示するには-
手順1: AppDelegateクラスにデリゲートUNUserNotificationCenterDelegateを追加します。
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
手順2: UNUserNotificationCenterデリゲートを設定する
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
ステップ3:このステップでは、アプリがフォアグラウンドにある場合でもアプリにプッシュ通知を表示できます
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
ステップ4:このステップはオプションです。アプリがフォアグラウンドにあるかどうかを確認し、フォアグラウンドにある場合はローカルPushNotificationを表示します。
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {
let state : UIApplicationState = application.applicationState
if (state == .inactive || state == .background) {
// go to screen relevant to Notification content
print("background")
} else {
// App is in UIApplicationStateActive (running in foreground)
print("foreground")
showLocalNotification()
}
}
ローカル通知機能-
fileprivate func showLocalNotification() {
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "App Update"
//content.subtitle = "local notification"
content.body = "New version of app update is available."
//content.badge = 1
content.sound = UNNotificationSound.default()
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
notificationCenter.add(request, withCompletionHandler: nil)
}