본문 바로가기
iOS

[iOS] UNUserNotificationCenter를 이용해서 로컬 푸시하기!

by thoonk: 2021. 1. 5.

iOS앱에서 로컬 노티피케이션을 푸시하기 위해서 UNUserNotificationCenter를 사용해보겠습니다.

UNUserNotificationCenter는 앱 또는 앱의 확장에 대한 알림과 관련된 활동을 관리하기 위한 중심 객체라고 합니다.

 

alert, badge, sound를 통해 사용자에게 알림을 주고 알림을 스케쥴링할 수 있습니다. 

먼저 사용자에게서 권한을 얻어야 합니다. 

func requestNotiAuth() {
    let authOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
        
    UNUserNotificationCenter
        .current()
        .requestAuthorization(options: authOptions) { isSuccess, error in
        if let error = error {
            print(error.localizedDescription)
        }
    }
 }

 

위 예시처럼 func requestAuthorization(options: UNAuthorizationOptions, completionHandler: (Bool, Error?) -> Void) 메서드를 이용해서 권한을 요청할 수 있습니다. 

그리고 UNAuthorizationOptions를 통해 사용할 옵션들을 설정할 수 있습니다. 

 

이제 권한을 얻었으면 notification 스케쥴링을 해보겠습니다.

let notiContent = UNMutableNotificationContent()
notiContent.title = "알림제목"
notiContent.body = "알림 세부사항"
notiContent.sound = UNNotificationSound.default
            
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute], from: Date())
            
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notiContent, trigger: trigger)
            
UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("Notification Error:", error)
    }
}

UNMutableNotificationContent를 이용해서 보낼 알림을 설정해줍니다. 

그리고 저는 UNNotificationRequest를 통해서 원하는 날짜 및 시간에 알림을 푸시하도록 하겠습니다.

위 코드 상에서는 Date()로 되어있지만 원하는 날짜 및 시간을 DateFormatter 등을 이용해서 설정하시면 됩니다. 

로컬 알림을 예약을 요청하기 위해서 UNNotificationRequest 메서드에 범용 고유 식별자 UUID, 알림 설정한 content, trigger를 입력해줍니다. 

그리고 그 request를 func add(UNNotificationRequest, withCompletionHandler: ((Error?) -> Void)?)를 이용해서 추가합니다. 

 

여기서 끝이 아니라 .. AppDelegate에 Delegate를 추가해줘야 알림을 푸시할 수 있습니다.

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                        didReceive response: UNNotificationResponse,
                        withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
    
   func userNotificationCenter(_ center: UNUserNotificationCenter,
                        willPresent noti: UNNotification,
                        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.list, .sound, .badge, .banner])
    }
}

저는 background, foreground 모두 푸시를 받도록 했고 소리와 뱃지가 추가되도록 했습니다.

 

만약 스케쥴링에 추가된 알림 요청을 지우고 싶다면 .. ?

UNUserNotificationCenter.current().getPendingNotificationRequests { (notiRequests) in
    var removeIdentifiers = [String]()
    for noti: UNNotificationRequest in notiRequests {
        for id in identifiers {
            if noti.identifier == id {
                removeIdentifiers.append(noti.identifier)
            }
        }
    }
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: removeIdentifiers)
}

func getPendingNotificationRequests(completionHandler: ([UNNotificationRequest]) -> Void) 메서드를 이용해서 현재 요청된 알림들을 탐색합니다.

그리고 그 중에 지우고 싶은 identifiers를 찾으면 String 배열에 추가합니다. 그 이유는 func removePendingNotificationRequests(withIdentifiers: [String]) 파라미터 타입이 [String]이기 때문입니다. 

 

이렇게 로컬 노티피케이션에 대한 내용을 정리해봤습니다.

 

참조:

UNUserNotification

 

Apple Developer Documentation

 

developer.apple.com

UNMutableNotificationContent

 

Apple Developer Documentation

 

developer.apple.com

'iOS' 카테고리의 다른 글

[iOS] 시뮬레이터에서 할 수 없는 것들  (0) 2021.01.12
[iOS] Frame과 Bounds의 차이  (0) 2021.01.12
[iOS] User Notification  (1) 2020.12.29
[iOS] Label에 취소선 긋기  (1) 2020.12.24
[iOS] JSON 파싱  (0) 2020.12.04

댓글