본문 바로가기
iOS Swift/Study

[Swift] 알람앱 - 타이머(7) 로컬 푸쉬 알림 구현

by 야고이 2024. 5. 21.
728x90

사용자에게 알람 허용 요청

앱을 가장 처음 실행 할 때 알림 허용을 요청해야합니다

앱을 실행하고 가장 처음 보여지는 화면 viewWillApear 에서 알림 허용 요청 얼럿창을 띄어줍니다

import UserNotifications

 

 

사용자에게 알람 허용을 요청할 메서드 구현

let userNotificationCenter = UNUserNotificationCenter.current()

override func viewWillAppear(_ animated: Bool) {
    requestNotificationAuthorization()
}

func requestNotificationAuthorization() {
    let authOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)

    userNotificationCenter.requestAuthorization(options: authOptions) { success, error in
        if let error = error {
            print("Error: \(error)")
        }
    }
}

앱을 첫실행 할때 알림 허용 얼럿이 뜨고 설정에서도 알림에 관한 설정을 바꿀 수 있습니다

 


타이머 종료시 push 알림 보내기

import UserNotifications

let userNotificationCenter = UNUserNotificationCenter.current()

 // MARK: - UserNotification
    func sendNotification(seconds: Double) {
        let notificationContent = UNMutableNotificationContent()
        
        notificationContent.title = "WakeUpClock"
        notificationContent.body = "타이머 종료"
        notificationContent.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "Stargaze.mp3"))
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: seconds, repeats: false)
        let request = UNNotificationRequest(identifier: "testNotification",
                                            content: notificationContent,
                                            trigger: trigger)
        
        userNotificationCenter.add(request) { error in
            if let error = error {
                print("Notification Error: ", error)
            }
        }
    }

이 함수를 타이머 실행 시키는 함수에 호출해주었습니다

파라미터의 seconds 에는 실행하는 타이머의 시간이 들어갑니다

title 과 body 가 push 알림에 보여짐

// 타이머 실행 코드
func setTimer(with countDownSeconds: Int) {
    print("countDownSeconds: \(countDownSeconds)")
    timerState = .started
    updateTimerState()

    let startTime = Date()
    timer.invalidate() // 기존에 실행된 타이머 중지
    remainTime.text = self.convertSecondsToTime(timeInSeconds: countDownSeconds)
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] timer in
        let elapsedTimeSeconds = Int(Date().timeIntervalSince(startTime)) // 경과된 시간
        let remainSeconds = Int(countDownSeconds) - elapsedTimeSeconds
        guard remainSeconds >= 0 else {
            timer.invalidate() // 0초 되면 타이머 중지
            self?.timerState = .finished
            self?.updateTimerState()

            return
        }
        self?.setTime = remainSeconds
        self?.remainTime.text = self?.convertSecondsToTime(timeInSeconds: remainSeconds)
        self?.sendNotification(seconds: Double(countDownSeconds)) // push 알림 실행
    })
}

 

사운드는 파일을 다운받아서 넣어주었습니다

 

 

앱을 완전 종료해도 push 알림이 온다

 

 

참고 블로그

 

728x90

댓글