티스토리 뷰
# 개요
- 사용자 알림(User Notifications)은 앱의 실행 여부에 관계 없이 앱 사용자에게 중요한 정보를 전달한다.
- 또한 알림은 앱에 정보를 다운로드하고 인터페이스 업데이트하도록 지시할 수도 있다.
- 알림은 로컬에서 생성하거나 서버에서 원격으로 생성할 수 있다.
- 여기서는 로컬에서 생성하는 알림에 대해서 알아보겠다.
# 알림 사용 권한 얻기
- 알림을 사용하기 위해선 앱 사용자에게 권한을 얻어야 한다.
- 알림 권한을 얻는 방법은 2가지가 있다.
1. 상황에 맞게 명시적으로 권한 요청하기
2. 임시 승인을 사용하여 평가판 알림 보내기
# 상황에 맞게 명시적으로 권한 요청하기
- 권한을 요청하려면 UNUserNotificationsCenter 인스턴스를 가져와 Authorization(options:completionHandler:) 메서드를 사용한다.
- options에 상호 작용 유형을 지정한다. (.alert : 알림 표시, .sound : 사운드 재생, .badge: 배지)
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
// 여기서 오류를 처리합니다.
}
// 인증에 따라 기능을 활성화 또는 비활성화합니다.
}
- 상황에 맞게 요청한다는 것은 앱이 처음 실행 시 권한을 요청하는 것이 아니라 알람을 사용하는 시점에 요청함으로서 사용자가 알림의 사용 목적을 더 쉽게 파악하게 하는 것이다.
# 임시 승인을 사용하여 평가판 알림 보내기
- 평가판 알림은 권한을 요청하지 않은 상황에서 임시 승인을 사용하여 알림을 보낸다.
- 사용자가 알림을 통해서 알림을 유지하거나 해제할 수 있는 버튼을 통해서 알림 권한 승인을 결정할 수 있게 된다.
- 시스템은 평가판 알림을 소리나 배너, 잠금 화면에 표시하지 않고, 알림 센터의 히스토리에만 표시하게 한다.
- 임시 승인을 요청하려면 알림 권한을 요청할 때, options에 .provisional을 추가하면 된다.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge, .provisional]) { ... }
# 현재 권한에 따라 알림 요청하기
- 로컬 알림을 예약하기 전에 항상 앱의 알림 권한 상태를 확인해야 한다.
- 사용가는 언제든지 앱의 권한을 변경할 수 있다.
- 알림 센터의 getNotificationSettings(completionHandler:) 메서드를 사용하면 현재 알림 설정을 얻을 수 있다.
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { settings in
guard (settings.authorizationStatus == .authorized) ||
(settings.authorizationStatus == .provisional) else { return }
if settings.alertSetting == .enabled {
// 알림 전용 알림을 예약합니다.
} else {
// 배지와 소리가 포함된 알림을 예약합니다.
}
}
- 위의 예에서는 가드 조건을 사용하여 앱이 승인되지 않은 경우, 알림 예약을 방지한다.
- 앱이 알림 권한이 없어도 알림을 구성할 수 있기 때문에 조심해야 한다.
- 앱이 포그라운드에 있으면 알림은 무시하게 된다.
- 하지만 알림 센터 델리게이트의 userNotificationCenter(_:willPresent:withCompletionHandler:) 메서드는 앱이 포그라운드에 있어도 알림을 수신하여 알림, 사운드, 배지 정보에 접근할 수 있게 한다.
# 앱에서 로컬로 알림 사용하는 방법
1. 알림 콘텐츠 만들기
- UNMutableNotificationContent에 알림 정보를 채운다.
- 제목, 부제목, 배지, 사운드 등 다양한 정보를 설정할 수 있다.
let content = UNMutableNotificationContent()
content.title = "Weekly Staff Meeting"
content.body = "Every Tuesday at 2pm"
- bagde 속성은 배지 정보를 나타낸다.
- 0은 배지 정보를 삭제하고, 0보다 큰 값은 해당 값을 배지에 나타내게 한다.
- 배지 정보를 설정하지 않으면 nil이 된다.
- 배지 속성이 nil이면 이전 배지 정보를 그대로 사용하게 된다.
- 배지는 시스템이 카운터를 하지 않기 때문에 개발자가 상황에 맞는 배지 값으로 수동으로 설정해야 한다.
2. 알림 발생 조건 지정하기
- 트리거 객체를 통해서 알림 발생 조건을 지정한다.
- 날짜 조건 : UNCalendarNotificationTrigger
- 시간 조건 : UNTimeIntervalNotificationTrigger
- 위치 조건 : UNLocationNotificationTrigger
// 반복되는 날짜를 구성한다.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3 // Tuesday
dateComponents.hour = 14 // 14:00 hours
// 트리거를 반복 이벤트로 만든다.
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents, repeats: true)
3. 알림 요청 생성하기
// 요청을 만든다.
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: content, trigger: trigger)
4. 알림 등록하기
// 시스템으로 요청을 예약한다.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// 에러를 처리한다.
}
}
5. 예약된 알림 요청 취소하기
- 예약된 알림은 트리거 조건이 충족될 때까지 활성 상태로 유지된다.
- 예약된 알림은 사용자가 명시적으로 취소를 하거나 앱을 삭제하면 삭제 된다.
- 예약된 알림을 취소하려면 UNUserNotificationCenter의 removePendingNotificationRequests(withIdentifiers:) 메서드를 사용해서 특정 알람을 취소할 수 있다.
- withIdentifiers에 String 타입의 uuid를 배열로 전달해야 한다.
- 다음 예제 코드는 SwiftUI에서 알림 정보를 가진 배열인 pendingNotifications의 특정 인덱스의 알람을 취소하는 메서드가 된다.
private func onDelete(indicex: IndexSet) {
let selectedNotifications = indicex.map { i in pendingNotifications[i] }
let selectedNotificationUUIDs = selectedNotifications.map { notification in
notification.identifier
}
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: selectedNotificationUUIDs)
pendingNotifications.remove(atOffsets: indicex)
}
- 또는 removeAllDeliveredNotifications() 메서드를 사용해서 모든 알람을 취소할 수 있다.
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
# 요청된 알림 조회하기
- 알림 센터의 getPendingNotificationRequests(completionHandler:) 메서드를 사용해서 요청된 모든 알림을 조회할 수 있다.
var pendingNotifications: [UNNotificationRequest] = []
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { notificationRequests in
pendingNotifications = notificationRequests
}
'UserNotifications' 카테고리의 다른 글
[UserNotifications] 로컬 알림을 설계하기 전에 알면 좋은 정보들 (0) | 2023.08.24 |
---|