[TIL] 무한반복 알람 중지시키기

한철희·2024년 5월 23일
0

TIL

목록 보기
45/57

이번 프로젝트에서 알람앱 + 기상미션을 추가한 앱을 만들었다
알람이 단발성으로 끝나는것이 아닌 사용자가 기상미션을 완료할 때까지 반복적으로 재생하는것으로 설정했다.

프로젝트를 위해 급하게 구현하여 올바른 방법이 아닐 수 있습니다!

func playAlarmSound() {
        guard let soundURL = SoundManager.shared.alarmSoundURL else {
            print("사운드 파일을 찾을 수 없습니다.")
            return
        }
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.play()
        } catch {
            print("사운드 파일 재생 중 오류 발생: \(error)")
        }
    }
    
func stopAlarmSound() {
     audioPlayer?.stop()
}

AppDelegate에 위와 같은 함수를 선언 해놨고

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if #available(iOS 14.0, *) {
            completionHandler([.banner, .sound])
            playAlarmSound()
        } else {
            completionHandler([.alert, .sound])
        }
    }

이와 같은 방식으로 배너가 뜨면서 소리가 나도록 설정했다.
그리고 배너를 클릭한 뒤 MissionVC화면이 뜨는데
여기서도 알람이 울리도록 하기 위해
다음과 같이 작성해줬다

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController {
            let wakeUpVC = MissionVC()
            wakeUpVC.modalPresentationStyle = .fullScreen
            rootViewController.present(wakeUpVC, animated: true, completion: nil)
        }
        playAlarmSound()
        completionHandler()
    }

같은 기능을 하는 더 좋은 방법이 있었을거같은데
일단은 위와 같은 방식으로 했다


이제 알람은 반복적으로 울릴테고
어떻게 멈추느냐가 중요한 부분인데
위의 코드를 보다시피 알람을 울리는 코드는 AppDelegate에 선언되어 있다
그래서 이것을 MissionVC에서 일어나는 특정 액션에 호출하여
중단시키는 것으로 구현했다.

//정답 버튼 클릭 시 사전페이지로
    private func successScreen() {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            // 소리 멈추기
            appDelegate.stopAlarmSound()
        }
        let successVC = MissionSuccessVC()
        successVC.modalPresentationStyle = .overFullScreen
        successVC.score = self.score //Total점수
        successVC.correctWord = self.currentWord //정답 맞힌 단어
        successVC.wrongCount = self.wrongCount //틀린 개수
        present(successVC, animated: true, completion: nil)
        
        Core.saveUser(user: User(score: self.score))
        
        //미션페이지의 작업 완료를 알림
        self.delegate?.missionVCDelegate()
    }

팀원분이 작성한 코드에 appDelegate 부분만 추가 작성했다.
이렇게 하면 MissionVC에서 정답처리시 다른 화면으로 넘어갈 때
반복되는 알람을 멈추고 넘어갈 수 있다.


아무래도 시간이 촉박한 프로젝트 기간에 하다보니
어떻게든 구현은 했지만 어색한 부분이 있고
더 좋은 방법이 있을거라 생각합니다

혹시나 더 좋은 방법을 알고계시면 알려주시면 감사합니다!

profile
초보 개발자 살아남기

0개의 댓글