티스토리 뷰

🍏/iOS

[iOS] Local Notification

eungding 2021. 5. 31. 15:28
반응형

User Notifications framework를 사용하여 Local Notification을 create & schedule 할 수 있습니다. 

 

 

[1] Asking Permission to Use Notifications 

 

Asking Permission to Use Notifications 문서 를 참고해주세요.

이런 얼럿을 띄워서 Notification 권한을 먼저 받아줍니다. 

 

보통 이 얼럿은 앱 처음 실행시킬 때 보여주잖아요! 

근데 문서에서는 사용자가 이 앱에 노티 권한이 필요한 이유를 이해할 수 있는 context에서 권한을 요청하라고 나와있습니다. 

 

예를들어 리마인드 노티를 보내주는 task-tracking 앱이라고 한다면,

사용자가 첫번째 Task를 예약한 후 이 권한을 요청하는 것이 좋습니다. 

 

이는 app first launch에 권한을 요청하는 것보다 더 좋은 사용자 경험을 제공합니다.

왜냐면 사용자는 노티가 어떤 용도로 사용되는 지 더 쉽게 알 수 있기 때문입니다. 

 

권한요청코드는 아래와 같습니다.

options에 여러개를 더 추가할 수 있는데 문서를 확인해주세요

 

 

[2] Get Notification Settings 

 

local notification을 스케쥴링 하기 전에 항상 권한을 확인해주세요 

사용자는 어느때던 authorization setting을 바꿀 수 있습니다. 

 

current notification setting은 notification center의 getNotificationSettings(completionHandler:)  로 구할 수 있습니다. 

여기서 구한 current setting에 따라 notification을 커스터마이징해주세요

 

아래 코드처럼 app이 not authorized한 경우에는 notification scheduling을 막고

허용되는 interaction의 type 에 따라 알림을 구성할 수 있습니다. 

 

그리고 notification center delegate의 userNotificationCenter(_:willPresent:withCompletionHandler:) 메소드는

app이 foreground에 있는 상태에서 notfication을 수신하고 alert, sound, badge information에 접근할 수 도 있습니다. 

 

 

[3] Create the Notification's Content 

 

여기서부터는 

Scheduling a Notification Locally from Your App 문서를 봐줬습니다. 

 

UNMutableNotificationContent Object를 만들고 notification이 deliver 해야하는 필드들을 채워줍니다. 

예를들어 sound를 재생하고 싶다면, sound property의 value를 설정해주면 됩니다. 

 

 

[4] Specify the Conditions for Delivery

 

딜리버리를 위한 조건을 명시합니다. 

UNCalendarNotificationTriggerUNTimeIntervalNotificationTrigger, UNLocationNotificationTrigger 중 하나를 쓰면되고

각 trigger object는 다른 파라미터를 요구합니다. 

 

참고로 위의 세개는 UNNotificationTrigger 의 서브클래스이고 

이름 그대로 각각 캘린더 / 시간(얼마나 지났는지) / Location(특정 지리적 지역에 사용자가 있는 지) 를 표현합니다. 

 

 

예를들어 calendar-based trigger는 date랑 time을 요구합니다. 

매주 화요일 2시에 알림이 오도록 구성해보겠습니다. 

DateComponents 를 이용해서 event의 타이밍을 명시해줬고 

trigger의 repeats  파라미터를 true로 해서 시스템이 delivery를 한 후에 event를 다시 reschedule할 수 있도록 해줬습니다. 

 

 

 

[5] Create and Register a Notification Request

 

3번 단계 에서 만든 content와  4번 단계에서 만든 trigger를 담고 있는 UNNotificationRequest object를 만들어줍니다.

그리고 add(_:withCompletionHandler:) 메소드를 통해 시스템에 우리의 request를 스케쥴링 해줍니다. 

 

 

[6] Cancel a Scheduled Notification Request 

 

한번 scheduled 되면, notification request는 특정 trigger 조건이 충족될 때까지 active한 상태로 유지됩니다.

명시적으로 notification request을 취소할 수 있습니다. 

 

보통 조건이 변경되어서 사용자에게 더 이상 알릴 필요가 없는 경우 

request를 취소합니다.

 

예를들어 사용자가 미리 알림을 완료하면 해당 미리 알림과 관련된 active requests를 모두 취소할 수 있습니다. 

active notification request를 취소하려면 

notification center의 removePendingNotificationRequests(withIdentifiers:) 메소드를 호출해주세요. 

 

 

 

[ 참고 ] 

 

Notification이 나오기 전에 메세지를 바꾸는 것은 Remote Notification일 때만 가능하다고 합니다.
(NotificationService extension을 추가하고 이 메소드를 활용하면 된다고 함)

 

 

[ 더 보면 좋을 것 ] 

 

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SchedulingandHandlingLocalNotifications.html

 

Local and Remote Notification Programming Guide: Scheduling and Handling Local Notifications

Local and Remote Notification Programming Guide

developer.apple.com

 

https://www.hackingwithswift.com/books/ios-swiftui/scheduling-local-notifications

 

Scheduling local notifications - a free Hacking with iOS: SwiftUI Edition tutorial

Was this page useful? Let us know! 1 2 3 4 5

www.hackingwithswift.com

 

반응형
댓글