UNUserNotificationCenter
UNUserNotificationCenter 클래스는 iOS에서 로컬 및 원격 알림을 관리하는 클래스이다. 이 클래스를 사용하여 알림을 생성, 수정, 삭제하고, 사용자의 알림 설정을 관리할 수 있다.
알림 권한 요청
기본적으로 앱에서 nofitication이 오게 되면 백그라운드에서 push알림이 오기 때문에 delegate을 채택해줘야 한다.
// AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// foreground에서도 notification을 받기위해 채택
UNUserNotificationCenter.current().delegate = self
return true
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
[.list, .banner, .sound, .badge]
}
}
UNUserNotificationCenter.current().requestAuthorization을 사용해서 권한요청을 한다.
options를 보면 (.alert, .badge, .sound) 등이 있는데 여러가지 옵션이 있으니 필요한 권한을 요청해준다.
// 권한 요청을 할 viewController
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound,]) { granted, error in
if granted {
print("권한 허용")
} else {
print("권한 거부")
}
}
Local Notification 보내기
UNMutableNotificationContent
Notification을 보내기 위해선 UNMutableNotificationContent를 생성해야한다.
UNMutableNotificationContent에는 title, body, sound, badge 등 다양한 설정이 가능하다.
UNNotificationTrigger
위에서 알림이 올 Notification을 만들어줬다면 "언제" 올 지를 지정해줘야한다.
UNNotificationTrigger는 특정시간, 시간간격, 위치변경을 기반으로 설정할 수 있다.
(UNTimeIntervalNotificationTrigger, UNCalendarNotificationTrigger, UNLocationNotificationTrigger, UNPushNotificationTrigger)
오늘은 가장 기본적은 UNTimeIntervalNotificationTrigger를 사용해볼 것이다.
UNNotificationRequest
이때까지 생성한 content와 trigger를 요청하는 클래스이다. 또한, 알림 요청의 고유 식별자도 함께 넘겨줘야 한다. (이때 사용된 고유 식별자는 스케줄링된 알림을 수정하거나 삭제할 때 사용된다.)
UNUserNotificationCenter
마지막으로 Notification을 보내기 위해 UNUserNotificationCenter에 add해준다.
(아래 코드의 본래형태는 UNUserNotificationCenter.current().add(request:, withCompletionHandler:)이다. )
func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Push 알림"
content.body = "Push 알림입니다."
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("스케줄링 실패: \(error.localizedDescription)")
} else {
print("스케줄링 성공")
}
}
}
이렇게 하면 성공적으로 Push 알림이 오게 된다!