ios

[ios - Swift] Foreground Push 알림 사용 (UNUserNotificationCenter 2/2)

POKY_0908 2020. 12. 6. 13:29

 

 

 

 

지난 글에서 알림을 Push 하는 것을 배웠습니다.

 

알림이 백그라운드 상태에서만 동작하기 때문에 이번 글에서는 포그라운드 상태에서 알림을 수신받을 수 있도록 코드를 추가해 보도록 하겠습니다.

 

UNUserNotificationCenter 사용법을 모르신다면 이곳에서 확인해 주세요.

 

 

 

 

1. userNotificationCenter 추가

앱이 포그라운드에서 실행되는 동안 도착한 알람을 처리하는 델리게이트입니다.

 

UNUserNotificationCenterDelegate에 다음 코드를 추가해 줍니다.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("identifier:\(notification.request.identifier)")
    completionHandler([.alert, .sound, .badge])
}

notification: 도착할 알람에 대한 정보입니다.

completionHandler를 통해 알람이 도착하면 실행할 옵션입니다.. alert이 없다면 알림이 안 오는 것처럼 보일 겁니다.

 

 

앱이 동작중에도 알림을 받는 것을 확인할 수 있습니다.