앱 또는 앱 확장에 대한 알림 관련 활동을 관리하기 위한 중앙 개체입니다.
UNUserNotificationCenter 개체를 사용하여 다음의 활동들을 할 수 있습니다.
import UserNotifications
@objc func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Authorized")
else {
print("Nope")
}
}
}
UNUserNotifiactionCenter.center() :
현재 앱의 UNUserNotificationCenter를 가져올 때인스턴스를 직접 만들지 않고 center()를 사용해서 얻어야합니다.
다음과 같이 작성하면 사용자에게 권한을 요청하는 alert가 뜨게 됩니다.
content와 trigger로 request를 쪼갠 이유는?
-> 서로 상호교환이 가능하기 때문이다. 예를 들어, 알림을 표시할 때 트리거는 특정 시간에 표시할 수도 있고, 시간 간격이 경과한 후 표시할 수도 있고, 위치를 기반으로 표시할 수도 있습니다.
무엇을 보여줄 지 작성하기 위해서는 UNMutableNotificationContent()를 사용해야합니다.
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.sound = UNNotificationSound.default
content.userInfo = ["customData": "fizzbuzz"]
content.categoryIdentifier = "alarm"
특정 시간에 보여주는 calendar trigger를 수행하기 위해서는 DateComponents를 사용해야합니다.
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponenets.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
만약 시간을 특정해서 설정하지 않고, 사용자가 지정한 Date로 trigger를 작성하고 싶다면
let dateComponents = Calendar.current.dateComponetns([.hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString,content: content, trigger: trigger)
center.add(request)
Notification 실행 전 추가하면 좋은 작업들
center.removeAllPendingNotificationRequests()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
추가로, Cmd+L을 누르면 디바이스를 잠금상태로 변경할 수 있습니다.
사용자의 응답에 따라 특정 행동을 취하기 위해서, 알림과 함께 옵션을 표시하여 사용자가 선택할 수 있게 합니다.
content작성 시에 categoryIdentifier를 "alarm"로 지정하였기 때문에 alarm 타입의 알림이 뜰 것입니다.
사용자가 선택할 수 있는 버튼을 만들기 위해서 두 가지 클래스가 필요합니다.
알람에서 전송되는 모든 메시지를 뷰 컨트롤러에서 처리하기 위해 delegate를 설정해줍니다.
class ViewController : UIViewController, UNUserNotificationCenterDelegate {
}
let center = UNUserNOtificationCenter.current()
center.delegate = self
let show = UNNotificationAction(identifier: "show", title: "Tell me more...", options: .foreground)
identifier : 버튼이 눌려졌을 때 전송되는 식별자
title : 인터페이스에서 사용자에게 보여지는 텍스트
options : 버튼 액션과 관련된 선택사항
액션을 원하는 만큼 작성한 후 UNNotificationCategory로 그룹화해줍니다.
let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])
center.setNotificationCategories([category])
사용자 action을 수행하는 코드를 작성한 method는 어디서든 호출되어도 되지만 가장 안전한 장소는 notification 설정 method의 서두일 것이다.
notification의 content의 userInfo에 작성한 사용자 정의 데이터가 여기로 전달됩니다.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @esecaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
switch reponse.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
print("Defualt identifier")
case "show":
print("show more information...")
default:
break
}
completionHandler()