결론
**UNNotificationServiceExtension 를 Target으로 추가하고** didReceive(_:withContentHandler:) 내에서 푸시 노티피케이션을 커스텀 할 수 있다.
An object that modifies the content of a remote notification before it’s delivered to the user.
→ 사용자에게 전달되기 전에, remote notification 의 컨텐츠를 수정할 수 있도록 도와주는 객체입니다.
didReceive(_:witContentHandler)
메소드 내에서 구현하면 됩니다.해당 메소드를 사용하기 위한 조건)
mutable-content
값이 1 로 세팅되어 있어야 해당 메소드가 호출됩니다.이 메소드를 사용하여, 알림을 변경할 수 있습니다만, 메소드에서 작업을 수행하는데 제한된 시간이 있습니다.
제한된 시간 내에 완료하지 못하게 된다면, serviceExtensionTimeWillExpire()
메소드를 시스템에서 호출합니다.
위 메소드는 변경하고 싶은 사항에 대한 마지막 처리를 할 수 있는 마지막 기회입니다.
만약 제한된 시간 내에 처리하지 못한 콘텐츠에 대해서 처리하고 싶은 것이 없다면, 그냥 두면 본래 콘텐츠만 보여주게 됩니다.(커스텀되지 않은 컨텐츠만 보여준다는 뜻)
Xcode에 NotificationServiceExtension 을 추가한다
Frameworks and Libraries
에 FirebaseMessaging이 추가된지 확인할 것(FCM 이용 하는 경우)사용자 정의 이름으로 구성된 UNNotificationServiceExtension
을 따르는 객체에 코드를 작성한다.
(아래 코드는 Firebase FCM 기준입니다.)
import UserNotifications
import FirebaseMessaging
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent
guard let bestAttemptContent = bestAttemptContent else { return }
/* title과 body 커스텀 */
bestAttemptContent.title = "[Modified]" + bestAttemptContent.title
bestAttemptContent.body = "[Modified]" + bestAttemptContent.body
FIRMessagingExtensionHelper().populateNotificationContent(
bestAttemptContent,
withContentHandler: contentHandler)
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}