[iOS] 푸쉬알림을 받을 수 있는 UserNotifications 알아보자

eung7_·2022년 2월 10일
0

iOS

목록 보기
10/17

개요

앱을 사용하다보면 푸쉬알림을 받을 것을 동의하는 것과 동시에 이렇게 푸쉬알림을 받아본 적이 있을 것이다. 오늘 소개할 것은 애플에서 제공하고 있는 프레임워크 중에 하나인 User Notifications를 소개하려고 한다.

푸쉬알림에는 거시적으로 두 가지 종류가 있다. 인터넷 필요 없이 앱 내에서 작동하는 Local Notifications와 누군가가 불특정한 시간, 장소에서 알림이 필요할 때 사용하는 Remote Notifications가 있다. 후자의 경우는 서버와 관련되어 있기 때문에 Back-End나 구글에서 제공하고 있는 Firebase를 이용해야 하며 Apple Push Notification service(APNs)의 이해가 필요하다.

이번 포스트에서는 Local-Notifications를 알아보고자 한다. UserNotifications Framework를 사용해야 할 때, 다음과 같은 프로세스가 있다.

  1. 푸쉬알림의 유형을 정의한다.
  2. 푸쉬알림과 관련된 원하는 작업을 정의한다.
  3. 푸쉬알림을 예약한다.
  4. 전달된 알림을 처리한다.
  5. 사용자 지정 작업에 응답한다.

사실여기까지만 들어도 잘 모르겠다. 왜냐하면 내가 그랬다...ㅎㅎ 이제 본격적으로 어떻게 구현하는지 알아보자.

사용자에게 알림 동의 구하기


새로 설치한 앱을 열 때 이런 문구를 접해본 적이 있을 것이다. UserNotifications를 사용하기 위해서는 위와 같은 작업을 필수적으로! 해줘야 한다. requestAuthorization은 UNUserNotificationCenter의 인스턴스를 생성하면 가져올 수 있다. 그리고 알림과 함께 사용할 옵션들의 사용 동의를 사용자에게 요청한다.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    
    if let error = error {
        // Handle the error here.
    }
    
    // Enable or disable features based on the authorization.
}

Notification's Content 만들기

사용자에게 동의를 구했다면, 본격적으로 구체적인 알림을 만들 시간이다. UNMutableNotificationContent라는 객체를 생성하여 푸쉬알림에서 보여줄 Property에 접근할 수 있다. 이외에도 Sound설정과 같은 다양한 Property가 있으니 사용하면 된다.

let content = UNMutableNotificationContent()
content.title = "Weekly Staff Meeting"
content.body = "Every Tuesday at 2pm"

Notification Trigger 만들기

이제 푸쉬알림의 실체를 구현했다면, 알림이 사용자에게 보여질 조건을 설정해줘야 한다. 이 조건에는 3가지 객체가 있다. 구현하려는 목적에 따라서 이 3가지 중 하나를 사용하면 되겠다.

UNCalendarNotficationTrigger : 정해진 날짜나 시간에 알림 배송
UNTimeIntervalNotificationTrigger : 지정한 시간이 지난 후에 알림 배송
UNLocationNotificationTrigger : 지정한 위치에 있을 때 알림 배송

// 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)

위의 소스코드는 UNCalendarNotificationTrigger를 사용한 예시이다. repeats는 말그대로 이 조건을 반복할 것인가에 대한 물음이다.

Notification Request 생성하고 등록하기

이제 대망의 알림을 요청할 시간입니다!

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

// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
   if error != nil {
      // Handle any errors.
   }
}

만들었던 콘텐츠(Notification Content)와 조건(Notification Trigger)을 대상으로 UNNotificationRequest 객체를 생성해주어야 합니다. 그리고 add(_:withCompletionHandler:)를 호출하여 구현하고 싶은 메서드에 집어 넣어주기만 하면 됩니다. 또 한가지, 여기서 indentifier는 여러 가지 알림이 있을테니, 각 알림을 구별해줄 인자입니다.


조금 이해가 가셨는지 모르겠네요 ㅎㅎ.. 저도 이번에 처음 배워보는 Framework라서 많이 헷갈렸습니다. 도움이 되셨으면 좋겠네요 !
https://developer.apple.com/documentation/usernotifications/

profile
안녕하세요. iOS 개발자 eung7입니다.

0개의 댓글