Day 70 - UNUserNotificationCenter

sun02·2021년 12월 9일
0

100 days of Swift 

목록 보기
37/40

UNUserNotificationCenter란?

앱 또는 앱 확장에 대한 알림 관련 활동을 관리하기 위한 중앙 개체입니다.

UNUserNotificationCenter 개체를 사용하여 다음의 활동들을 할 수 있습니다.

  • Asking Permission to Use Notifications :
    알림을 표시하거나, 소리를 재생하거나, 알림에 대한 응답으로 앱 아이콘에 배지를 표시할 수 있는 권한 요청
  • Declaring Your Actionable Notification Types :
    알림을 차별화하고 알림 인터페이스에 작업 버튼 추가
  • Scheduling a Notification Locally from Your App : 언제 사용자의 관심을 끌고싶은지 앱에서 알림 만들고 예약
  • Handling Notifications and Notification-Related Actions:
    알림 인터페이스를 사용한 사용자 상호 작용 관리
  • Manage the already delivered notifications the system displays in Notification Center. See Managing Delivered Notifications.
    : 전달받은 알림 관리
  • Get the notification-related settings for your app.

출처 - apple 문서

1. UserNotification framework

import UserNotifications
  • 위의 작업들을 수행하기 위해 가장 먼저 UseNotifications를 Import합니다.

2. 사용자에게 알림 권한 요청하기

@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가 뜨게 됩니다.

3. Notification 설정(content, trigger, request)

  • content : 무엇을 보여줄 지
  • trigger : 언제 보여줄 지
  • request: content + trigger

content와 trigger로 request를 쪼갠 이유는?
-> 서로 상호교환이 가능하기 때문이다. 예를 들어, 알림을 표시할 때 트리거는 특정 시간에 표시할 수도 있고, 시간 간격이 경과한 후 표시할 수도 있고, 위치를 기반으로 표시할 수도 있습니다.

- Content 작성하기

무엇을 보여줄 지 작성하기 위해서는 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"
  • title : 알림의 제목
  • body : 알림의 본문
  • sound : 알림 소리
    • UNNotificationSound를 사용해서 커스텀 소리를 만들 수도 있음
  • userInfo : userInfo Dictionary로 사용자 지정 데이터를 알림에 넣음
  • categoryIdentifier : 알림 유형을 나타내는 식별자

- Trigger(특정 시간에 표시)작성하기

특정 시간에 보여주는 calendar trigger를 수행하기 위해서는 DateComponents를 사용해야합니다.

var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponenets.minute = 30

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
  • 다음과 같이 작성하면 매일 10시 30분에 반복적으로 알림이 울립니다
    • repeats: false로 한다면, 내일 10시 30분에만 울립니다.

만약 시간을 특정해서 설정하지 않고, 사용자가 지정한 Date로 trigger를 작성하고 싶다면

let dateComponents = Calendar.current.dateComponetns([.hour, .minute], from: date)

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
  • 위와 같이 타입이(Date)인 date를 넣어주면 됩니다.

- Request(trigger + content)


let request = UNNotificationRequest(identifier: UUID().uuidString,content: content, trigger: trigger)

center.add(request)
  • 각 request에도 고유 식별자가 필요하기 때문에 UUID().uuidString을 사용해서 고유 식별자를 생성합니다.
    • 이름은 신경쓰지 않고 고유한 이름만을 원할 때

- Additional

Notification 실행 전 추가하면 좋은 작업들

center.removeAllPendingNotificationRequests()
  • 보류 중인 알림을 취소해줍니다.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  • 캘린더 트리거는 바로 실행되지 않으므로 다음과 같이 TimeInterval 트리거를 만들어줄 수 있습니다.

추가로, Cmd+L을 누르면 디바이스를 잠금상태로 변경할 수 있습니다.

4. 사용자 Action

사용자의 응답에 따라 특정 행동을 취하기 위해서, 알림과 함께 옵션을 표시하여 사용자가 선택할 수 있게 합니다.

content작성 시에 categoryIdentifier를 "alarm"로 지정하였기 때문에 alarm 타입의 알림이 뜰 것입니다.
사용자가 선택할 수 있는 버튼을 만들기 위해서 두 가지 클래스가 필요합니다.

  • UNNotificationAction : 사용자가 탭할 개별 버튼 생성
  • UNNotificationCategory : 생성된 여러 버튼을 단일 식별자 아래에서 그룹화

- delegate

알람에서 전송되는 모든 메시지를 뷰 컨트롤러에서 처리하기 위해 delegate를 설정해줍니다.

class ViewController : UIViewController, UNUserNotificationCenterDelegate {

}
  • 먼저 viewController에 UNUserNotificationCenterDelegate 프로토콜 추가
let center = UNUserNOtificationCenter.current()
center.delegate = self
  • center의 delegate를 self(현재 viewController)로 지정

- UNNotificationAction

let show = UNNotificationAction(identifier: "show", title: "Tell me more...", options: .foreground)
  • identifier : 버튼이 눌려졌을 때 전송되는 식별자

  • title : 인터페이스에서 사용자에게 보여지는 텍스트

  • options : 버튼 액션과 관련된 선택사항

    • .foreground = 앱 즉시 실행함
    • .destructive = 액션 사라짐(파괴적인 작업 수행)
    • .authenticationRequired = 장치 잠금을 해제하라는 메시지를 표시 (잠금 해제된 장치에서만 작업을 수행)

    더 자세히 - apple documents

- UNNotificationCategory

액션을 원하는 만큼 작성한 후 UNNotificationCategory로 그룹화해줍니다.

let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])

center.setNotificationCategories([category])
  • identifier : notification의 categoryIdentifier과 동일한 식별자 부여
  • actions: 작성한 UNNotificationAction들의 배열
  • intentIdentifiers : 알림과 연결하려는 intent의 식별자 배열

- 어디에 사용자 action Method를 추가할지?

사용자 action을 수행하는 코드를 작성한 method는 어디서든 호출되어도 되지만 가장 안전한 장소는 notification 설정 method의 서두일 것이다.

5. didReceive (사용자 action 이후 수행되는 것)

notification의 content의 userInfo에 작성한 사용자 정의 데이터가 여기로 전달됩니다.

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @esecaping () -> Void) {

	

- userInfo dictionary 받아오기

let userInfo = response.notification.request.content.userInfo
  • userInfo dictionary를 받아옵니다.
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
}
  • userInfo 딕셔너리에서 "customData" 키의 값이 존재한다면 아래 코드를 실행하도록 합니다
    • content의 userInfo에 ["customData": "fizzbuzz"]라고 작성하였기 때문에 여기서 customData에 들어가는 값은 "fizzbuzz"입니다.
  • 사용자가 알림에 대해 action을 취했을 때 그 response의 actionIdentifier를 받아옵니다
  • UNNotificationDefaultActionIdentifier: 사용자가 알림을 스와이프하여 장치 잠금을 해제한 경우
  • "show" : 사용자가 우리가 설정한 show 버튼을 탭한 경우/ 우리가 작성한 show 버튼의 식별자

- completionHandler()

completionHandler()
  • customData를 읽어올 수 있든 없든 수행이 끝난 후엔 completionHandler를 꼭 호출해야합니다.
    @escaping : 현재 메서드에서 벗어나 나중에 사용될 수 있dma

0개의 댓글