[iOS][SwiftUI] 로컬로 알림 Notification 만들기

Madeline👩🏻‍💻·2023년 8월 30일
1

iOS study

목록 보기
12/50

😤

Notification

  • 기능: alert 경고 표시, sound 소리 재생, badge app icon 아이콘 배지 표시

  • 사용자가 원하는 중요한 정보를 전달하기 위해 사용!

  • 앱이 실행되지 않았거나, 백그라운드: 시스템이 대신 사용자와 상호작용

  • 앱이 포그라운드: 시스템은 앱에 알림 전달

Notification 내용

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

Notification 조건 -> Trigger

  • 객체를 사용하여 알림 조건을 지정
  • 각 트리거 개체에는 서로 다른 매개변수가 필요함

ex) 달력기반 트리거를 사용하려면, 배달 날짜, 시간을 지정해야 함
-> 매주 화요일 오후 2시에 알림 울리게 해줘

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

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.
   }
}

UNNotificationRequest

  • 로컬 노티를 요청하는걸로, 내용이랑 전달 조건을 포함합니당

  • UNNotificationContent

  • UNNotificationTrigger

  • 노티 예약하려면, request object를 add(_:withCompletionHandler:)에 넘깁니다!

  • request를 만들었다면, 객체와 인터랙트하는디

  • 앱의 임시 노티를 보고 싶어 -> getPendingNotificationRequests(completionHandler:)

  • 시스템이 앱으로 노티 전달 -> UNNotification - UNNotificationRequest object로 디테일 보기

  • 알림센터로부터 노티 지우고 싶어 -> identifier

Notification 취소

  • 일단 예약되면, 취소될때까지 활성 상태로 유지된다.
  • 조건이 변경되어 필요가 없어지면, 요청 취소한다!
    removePendingNotificationRequests(withIdentifiers:)
    UNUserNotificationCenter

실습을 해보아요.

LocalNotificationManager


import Foundation
import UserNotifications

struct Notification {
    var id: String
    var title: String
}

class LocalNotificationManager {
    var notifications = [Notification]()
    
    func requestPermission() -> Void {
        UNUserNotificationCenter
            .current()
            .requestAuthorization(options: [.alert, .badge, .alert]) { granted, error in
                if granted == true && error == nil {
                    //we have permission!
                }
            }
    }
    
    func addNotification(title: String) -> Void {
        notifications.append(Notification(id: UUID().uuidString, title: title))
    }
    
    func schedule() -> Void {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            switch settings.authorizationStatus {
            case .notDetermined:
                self.requestPermission()
            case .authorized, .provisional:
                self.scheduleNotifications()
            default:
                break
            }
        }
    }
    
    func scheduleNotifications() -> Void {
        for notification in notifications {
            //🗓️ 날짜 설정
            var dateComponents = DateComponents()
            dateComponents.calendar = Calendar.current
            dateComponents.weekday = 4 // Wednesday
            dateComponents.hour = 19 // 14:00
            
            let content = UNMutableNotificationContent()
            content.title = notification.title
            content.sound = UNNotificationSound.default
            content.subtitle = "약 먹을 시간이에요.💊"
            content.body = "먹었다고 체크하기"
            content.summaryArgument = "summary argument"
            content.summaryArgumentCount = 40
            
//            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: notification.id, content: content, trigger: trigger)
            
            UNUserNotificationCenter.current().add(request) { error in
                guard error == nil else { return }
                print("scheduling notification with id:\(notification.id)")
            }
        }
    }
    
    
}

View


import SwiftUI

struct ContentView: View {
    
    func setNotification() -> Void {
        let manager = LocalNotificationManager()
        manager.requestPermission()
        manager.addNotification(title: "")
        manager.schedule()
//        manager.scheduleNotificaitons()
    }
    var body: some View {
        VStack {
            Button(action: { self.setNotification()
            }) {
                Text("Noti!")
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

정확한 시간에 울리게 해보았읍니다
🥹

레퍼런쓰
https://developer.apple.com/documentation/usernotifications/scheduling_a_notification_locally_from_your_app
https://velog.io/@j_aion/SwiftUI-Local-Notifications
https://2unbini.github.io/%F0%9F%93%82%20all/swift/swiftUI-Local-Notification/

profile
Major interest in iOS 🍀 & 🍎

0개의 댓글