[swift] UNUserNotificationCenter

2024. 4. 5. 12:01·swift

UNUserNotificationCenter

UNUserNotificationCenter 클래스는 iOS에서 로컬 및 원격 알림을 관리하는 클래스이다. 이 클래스를 사용하여 알림을 생성, 수정, 삭제하고, 사용자의 알림 설정을 관리할 수 있다.

 

알림 권한 요청

기본적으로 앱에서 nofitication이 오게 되면 백그라운드에서 push알림이 오기 때문에 delegate을 채택해줘야 한다.

// AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // foreground에서도 notification을 받기위해 채택
        UNUserNotificationCenter.current().delegate = self
        
        return true
 }
 extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        [.list, .banner, .sound, .badge]
    }
}

UNUserNotificationCenter.current().requestAuthorization을 사용해서 권한요청을 한다.

options를 보면 (.alert, .badge, .sound) 등이 있는데 여러가지 옵션이 있으니 필요한 권한을 요청해준다.

// 권한 요청을 할 viewController
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound,]) { granted, error in
    if granted {
        print("권한 허용")
    } else {
        print("권한 거부")
    }
}

 

Local Notification 보내기

UNMutableNotificationContent

Notification을 보내기 위해선 UNMutableNotificationContent를 생성해야한다.

UNMutableNotificationContent에는 title, body, sound, badge 등 다양한 설정이 가능하다.

 

UNNotificationTrigger

위에서 알림이 올 Notification을 만들어줬다면 "언제" 올 지를 지정해줘야한다.

UNNotificationTrigger는 특정시간, 시간간격, 위치변경을 기반으로 설정할 수 있다.

(UNTimeIntervalNotificationTrigger, UNCalendarNotificationTrigger, UNLocationNotificationTrigger, UNPushNotificationTrigger)

오늘은 가장 기본적은 UNTimeIntervalNotificationTrigger를 사용해볼 것이다.

 

UNNotificationRequest

이때까지 생성한 content와 trigger를 요청하는 클래스이다. 또한, 알림 요청의 고유 식별자도 함께 넘겨줘야 한다. (이때 사용된 고유 식별자는 스케줄링된 알림을 수정하거나 삭제할 때 사용된다.)

 

UNUserNotificationCenter

마지막으로 Notification을 보내기 위해 UNUserNotificationCenter에 add해준다.

(아래 코드의 본래형태는 UNUserNotificationCenter.current().add(request:, withCompletionHandler:)이다. )

func scheduleLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Push 알림"
    content.body = "Push 알림입니다."
    content.sound = .default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)

    let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            print("스케줄링 실패: \(error.localizedDescription)")
        } else {
            print("스케줄링 성공")
        }
    }
}

 

이렇게 하면 성공적으로 Push 알림이 오게 된다!

 

'swift' 카테고리의 다른 글
  • [swift] Combine
  • [swift] File Manager
  • [swift] UserDefaults
  • [swift] 데이터 저장 방식
GwanSon
GwanSon
버그는 도전, 코드는 해결. 열정있는 개발을 하자.
  • GwanSon
    관슨의 개발일지
    GwanSon
  • 전체
    오늘
    어제
    • 분류 전체보기 (56)
      • iOS (3)
      • swift (15)
      • UIKit (0)
      • swiftUI (2)
      • 알고리즘 (8)
      • CS (8)
      • 면접 (11)
      • Flutter (4)
      • 회고 (2)
      • 잡담 (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Swift
    모듈화
    boj
    백준
    부스트캠프 10기
    부스트캠프
    토스
    ios
    네이버 부스트캠프 후기
    2025 토스 Next
    네이버 부스트캠프
    챌린지
    후기
    tuist
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
GwanSon
[swift] UNUserNotificationCenter
상단으로

티스토리툴바