원하는 시간에 맞춰 알림을 등록하고 싶을 때 사용할만한 방법. 서버가 필요하지 않은 알림은 LocalNotification으로 처리할 수 있다.
Create the notification's content
let content = UNMutableNotificationContent()
content.title = "Weekly Staff Meeting"
content.body = "Every Tuesday at 2pm"
- UNMutableNotificationContent를 생성해 title과 body에 원하는 문구를 저장한다.
- 필요한 경우 sound나 badge도 설정할 수 있다.
Specify the conditions for delivery
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3 // Tuesday
dateComponents.hour = 14 // 14:00 hours
// Create the trigger as a repeating event.
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
- 원하는 시간 또는 날짜에 localnotification을 쏴줄 수 있다.
- 위 코드는 매주 수요일 오후 2시에 발송되도록 설정해준 상태. 매일 발송되게 하려면 weekday 코드를 추가하지 않으면 된다.
Create and register a notification request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
do {
try await notificationCenter.add(request)
} catch {
// Handle errors that may occur during add.
}
- 위에서 설정했던 notification을 등록하는 코드. 유저에게 보여줄 content와 알림이 노출될 trigger를 활용해 request를 생성한다.
원문 article
Scheduling a notification locally from your app
[Scheduling a notification locally from your app | Apple Developer Documentation
Create and schedule notifications from your app when you want to get the user’s attention.
developer.apple.com](https://developer.apple.com/documentation/usernotifications/scheduling-a-notification-locally-from-your-app)
추후에 더 보면 좋을 article
Handling notifications and notification-related actions
[Handling notifications and notification-related actions | Apple Developer Documentation
Respond to user interactions with the system’s notification interfaces, including handling your app’s custom actions.
developer.apple.com](https://developer.apple.com/documentation/usernotifications/handling-notifications-and-notification-related-actions)
'Swift' 카테고리의 다른 글
Sheet와 FullScreen은 공존할 수 없다 (0) | 2025.02.02 |
---|---|
ARC(Automatic Reference Counting) - Strong Reference Cycles for Closures (0) | 2023.02.16 |
ARC(Automatic Reference Counting) - 강한 순환 참조와 Weak, Unowned (0) | 2023.02.16 |
ARC(Automatic Reference Counting) - What is ARC? (1) | 2023.02.15 |
Self vs self (0) | 2023.02.03 |