iOS - UserNotification

이한솔·2023년 11월 28일
0

iOS 앱개발 🍏

목록 보기
33/49

UserNotification

UserNotification을 이용하면 로컬 및 원격 푸시 알림을 관리할 수 있다.



UserNotification 사용방법

  1. UserNotifications을 import한다.
import UserNotifications
  1. 앱 시작 시 사용자에게 푸시 알림 권한을 요청한다.
    requestAuthorization 메소드의 completionHandler에 권한 허용 여부를 받아 올 수 있다.
    권한 허용을 거부하면 알림을 받을 수 없다.
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().delegate = self
    let userNotificationCenter = UNUserNotificationCenter.current()
    let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
        
    userNotificationCenter.requestAuthorization(options: authOptions) { success, error in
        if let error = error {
            print(error)
        }
    }
    return true
}
  1. 알림을 보내고 싶은 순간에 알림을 예약한다.

  2. UNMutableNotificationContent클래스의 인스턴스를 생성해서 알림의 title이나 sound등 다양한 설정을 할 수 있다.
    badge를 설정하면 앱의 아이콘에 알림 개수를 띄울 수 있다.

  3. 알림이 언제 발생할지 트리거를 설정한다.

💡 트리거 종류

시간 기반 트리거 (Time-Based Triggers)
UNTimeIntervalNotificationTrigger: 특정 시간 간격이 지난 후 알림을 트리거합니다. 예를 들어, 5분 후에 알림을 보내는 등의 시나리오에 사용됩니다.

달력 기반 트리거 (Calendar-Based Triggers)
UNCalendarNotificationTrigger: 특정 날짜와 시간에 알림을 트리거합니다. 달력 이벤트에 따라 알림을 예약하는 데 사용됩니다.

위치 기반 트리거 (Location-Based Triggers)
UNLocationNotificationTrigger: 특정 지리적 위치에 도달하거나 떠날 때 알림을 트리거합니다. 사용자가 특정 장소에 도착하거나 떠날 때 특정 작업을 수행하도록 하는 데 사용됩니다.

인터벌 기반 트리거 (Repeating Triggers)
UNTimeIntervalNotificationTrigger: 특정 시간 간격을 기반으로 주기적으로 반복되는 알림을 트리거합니다. 예를 들어, 매일 같은 시간에 알림을 보내는 등의 시나리오에 사용됩니다.

사용자 정의 트리거 (Custom Triggers)
앱에서 사용자 정의 트리거를 정의하고 구현하여 특정 이벤트나 조건에 따라 알림을 트리거할 수 있습니다. 이는 앱의 고유한 요구사항에 따라 다양한 시나리오에 유용합니다.
  1. UNNotificationRequest 클래스를 이용해서 알림을 요청한다.
    만든 content와 트리거와 알림의 고유 식별자 이름을 정해서 넘겨준다.

  2. UNUserNotificationCenter에 add해서 알림을 예약한다.
    UNUserNotificationCenter는 예약된 알림요청들을 처리해주는 알림센터같은 역할을 한다.

func scheduleNotification() {
    // 알림 내용 등 설정
    let content = UNMutableNotificationContent()
    content.title = "알림 제목"
    content.body = "알림 내용"
    content.sound = UNNotificationSound.default
    
    // 알림 트리거 설정
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    // 알림 요청 생성
    let request = UNNotificationRequest(identifier: "notificationIdentifier", content: content, trigger: trigger)
    
    // 알림 예약
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error {
            print("알림 예약 중 오류 발생: \(error)")
        } else {
            print("알림이 성공적으로 예약되었습니다.")
        }
    }
}

0개의 댓글