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 에는 실행하는 타이머의 시간이 들어갑니다

// 타이머 실행 코드
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 알림 실행
})
}
사운드는 파일을 다운받아서 넣어주었습니다



728x90
'iOS Swift > Study' 카테고리의 다른 글
[Xcode Swift] Api 키 숨기기 (1) | 2024.06.03 |
---|---|
[Swift] 알람앱 - 타이머(6) 최근 타이머 목록 저장, 삭제, 실행 (0) | 2024.05.21 |
[Swift] 알람앱 - 타이머(5) 테이블뷰 높이 동적으로 그리기 (0) | 2024.05.21 |
[Swift] 알람앱 - 타이머(4) 상태변화에 따라서 UI 변경 및 로직 구현(시작, 일시정지, 재시작, 취소) (2) | 2024.05.16 |
[Swift] 알람앱 - 타이머(3) - 타이머 초를 HH:MM:SS 포맷으로 보여주기 (0) | 2024.05.15 |
댓글