[iOS] UserNotifications

Eugenie·2022년 8월 26일
0

UserNotifications

Push user-facing notifications to the user’s device 
from a server, or generate them locally from your app.

서버에서 사용자 장치로 사용자 대면 알림을 푸시하거나
앱에서 로컬로 생성하는 것을 말한다.

사용자 대면 알림
앱이 사용자의 기기에서 실행중인지 여부에 관계없이
앱 사용자에게 중요한 정보를 전달한다.

Asking Permission to Use Notifications

Request permission to display alerts, play sounds, 
or badge the app’s icon in response to a notification.

알림을 표시하거나, 소리를 재생하거나, 알림에 대한 응답으로
앱 아이콘에 배지를 표시할 수 있는 권한을 요청하는 것을 말한다.

로컬 및 원격 알림은 경고를 표시하거나, 소리를 재생하거나,
앱 아이콘에 배지를 지정하여 사용자의 주의를 끈다.

이러한 상호작용은 앱이 실행되고 있지 않거나 백그라운드에 있을 때 발생하는데
사용자가 볼 수 있는 관련 정보가 앱에 있음을 사용자에게 알린다.

사용자가 알림 기반 상호작용을 방해한다고 생각할 수 있으므로
사용 권한을 얻어야 한다.

// Documents example
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.
}

공식문서에는 위와 같은 예시 코드가 포함되어있다.

let userNotificationCenter = UNUserNotificationCenter.current()

let authorizationOptions = UNAuthorizationOptions(arrayLiteral: [.alert, .badge, .sound])

userNotificationCenter.requestAuthorization(options: authorizationOptions) { _, error in
	if let error = error {
		print("ERROR: notification authrization request \(error.localizedDescription)")
    }
}

공식문서의 예시와는 다르게 위와 같이 작성할 수도 있다.

UNNotification Request

UNNotification Request 에서 UNUserNotification 의 약자이다.

UNNotification 의 필수요소 3가지는 다음과 같다.

🌀 identifier

각 요청을 구분할 수 있는 id 를 말한다.
고유한 값인 UUID 를 입력하는 것이 일반적이다.

🌀 content

UNMutableNotificationContent

알림에 나타날 내용들을 정의한다.

( 알림에 표시될 title 이나 내용, 알림소리, 뱃지에 표시될 내용 등 )

🌀 trigger

UNCalenderNotificationTrigger - 달력, 날짜, 특정 시점
UNTimeIntervalNotificationTrigger - 일정 시간마다
UNLocalNotificationTrigger - 사용자의 위치에 따라

UNMutableNotificationContent

The editable content for a notification.

알림에 나타날 내용들을 정의할 수 있다.

// Configure the notification's payload.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationStringForKey("Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationStringForKey("Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
 
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) // Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
     if let theError = error {
         // Handle any errors
     }
}
❗️알림으로 인해 뱃지가 보여진 후, 앱을 실행한다고해서 뱃지가 사라지는 것은 아니므로 처리가 필요하다.
// SceneDelegate.swift

// 사용자가 앱을 열어서, scene 이 Active 상태가 되었을 때
func sceneDidBecomeActive(_ scene: UIScene) {
	// badge 를 없애준다.
    UIApplication.shared.applicationIconBadgeNumber = 0
}

Trigger

UNCalendarNotificationTrigger

A trigger condition that causes a notification the system delivers 
at a specific date and time.

특정 날짜 및 시간에 알림이 전달되도록 하는 트리거 조건을 말한다.

// Documents example
var date = DateComponents()
date.hour = 8
date.minute = 30 
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

공식문서에는 위와 같은 예시 코드가 포함되어있다.

let component = Calendar.current.dateComponents(
												[.hour, .minute], 
												from: alert.date
                                               )
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: alert.isOn)

공식문서의 예시와는 다르게 위와 같이 작성할 수도 있다.

devMatching 은 트리거를 구성할 때 사용할 시간정보를 넣어주면 된다.

repeats 는 반복해서 알림을 전달할 것인지에 대한 정보를 넣어주는 것이다.
알림을 한 번만 전달할 것이라면 false 를 지정하고,
시스템이 알림을 전달할 때마다 알림 요청을 다시 예약하려면 true 를 지정하면 된다.

UNTimeIntervalNotificationTrigger

A trigger condition that causes the system to deliver a notification 
after the amount of time you specify elapses.

지정한 시간이 경과한 후 알림이 전달되도록 하는 트리거 조건을 말한다.

// Fire in 30 minutes (60 seconds times 30)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (30*60), repeats: false)

UNLocationNotificationTrigger

A trigger condition that causes the system to deliver a notification 
when the user’s device enters or exits a geographic region you specify.

사용자의 장치가 지정한 지역에 들어오거나 나갈 때
알림이 전달되도록 하는 트리거 조건을 말한다.

let center = CLLocationCoordinate2D(latitude: 37.335400, longitude: -122.009201)
let region = CLCircularRegion(center: center, radius: 2000.0, identifier: "Headquarters")
region.notifyOnEntry = true
region.notifyOnExit = false
let trigger = UNLocationNotificationTrigger(region: region, repeats: false)

UNNotificationRequest

A request to schedule a local notification, 
which includes the content of the notification 
and the trigger conditions for delivery.

알림의 내용과 전달을 위한 트리거 조건을 포함하는
로컬 알림 예약 요청을 말한다.

let request = UNNotificationRequest(
									identifier: alert.id, 
									content: content, 
									trigger: trigger
								   )

앞서 작성하였던 request 의 3요소를 설정해주면 된다.

UNNotificationCenter

편지를 작성하여 우체국을 가거나 우체통에 편지를 넣는 행위와 같이
어떤 알림을 보낼 것인지 request 를 작성하고
NotificationCenter 에 추가하는 과정이 필요하다.

let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
     if let theError = error {
         // Handle any errors
     }
}

UNMutableNotificationContent 의 예시코드에 전반적인 내용이 모두 담겨있었다.
해당 코드는 다음과 같다.

// Configure the notification's payload.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationStringForKey("Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationStringForKey("Hello_message_body", arguments: nil)
content.sound = UNNotificationSound.default()
 
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) // Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
     if let theError = error {
         // Handle any errors
     }
}

📚 Reference
UserNotification
Asking Permission to Use Notification
getNotificationSettings(completionHandler:)
UNCalendarNotificationTrigger
UNCalendarNotificationTrigger-initializer
DateComponents
UNTimeIntervalNotificationTrigger
UNLocationNotificationTrigger
UNNotificationRequest
UNNotificationRequest-initializer
UNUserNotificationCenter
[iOS] Local Notification

profile
🌱 iOS developer

0개의 댓글