Swift에서 UserDefaults를 활용한 로컬 알림 설정 방법

sonny·2025년 2월 24일
0

TIL

목록 보기
137/140

1. 문제 상황

앱에서 로컬 알림을 예약할 때, 사용자 맞춤 이름을 포함해 "소소한 행복을 적어 [이름]를 키워주세요."라는 메시지를 띄우려고 했다. 하지만 기본값 "행담이"만 출력되었고, UserDefaults에서 저장한 사용자 이름이 반영되지 않았다.

또한, 사용자가 알림 시간을 변경하면 기존 예약을 취소하고 새로운 시간을 설정해야 했다.

2. 해결 방법

(1) UserDefaults에서 값 가져오기

이름과 알림 시간을 저장하고, 가져오는 코드를 추가했다.

let name = UserDefaults.standard.string(forKey: "name") ?? "행담이"

이를 통해 UserDefaults에 저장된 값이 없다면 기본값 "행담이"를 사용하도록 했다.

(2) 알림 예약 시 최신 값 반영

기존에는 알림을 예약할 때 name을 직접 하드코딩했지만, UserDefaults에서 값을 불러와 반영하도록 수정했다.

1. 알림 예약 로직에서 이름을 가져와 사용

func setUserNotification() {
    let identifier = "SelectedTimeNotification"
    
    let time = UserDefaultsManager.shared.getNotificationTime()
    let name = UserDefaultsManager.shared.getHangdamName()
    
    notificationCenter.removePendingNotificationRequests(withIdentifiers: [identifier])
    scheduleNotification(time: time, name: name, identifier: identifier)
}

2. 알림 메시지 생성 시 이름 반영

private func createNotificationContent(name: String, completion: @escaping (UNMutableNotificationContent) -> Void) {
    DispatchQueue.main.async {
        let content = UNMutableNotificationContent()
        content.title = "Sodam"
        content.body = "소소한 행복을 적어 \(name)를 키워주세요."
        content.sound = .default
        
        let currentBadgeNumber = UIApplication.shared.applicationIconBadgeNumber
        content.badge = NSNumber(value: currentBadgeNumber + 1)
        
        completion(content)
    }
}

(3) 사용자가 시간 변경 시 새로운 알림 예약

사용자가 UIDatePicker에서 시간을 변경할 때마다 기존 알림을 제거하고, 새롭게 예약되도록 했다.

private func scheduleNotification(time: Date, name: String, identifier: String) {
    createNotificationContent(name: name) { content in
        let trigger = self.createNotificationTrigger(for: time)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        self.notificationCenter.add(request) { error in
            if let error = error {
                DispatchQueue.main.async {
                    ToastManager.shared.showToastMessage(message: "알림 등록 실패: \(error.localizedDescription)")
                }
            }
        }
    }
}

3. 결론

기존에는 하드코딩된 값이 사용되었지만, UserDefaults에서 값을 즉시 가져와 사용하면서 최신 데이터를 반영할 수 있게 되었다.

이를 통해 다음과 같은 문제를 해결했다.
1. 사용자 맞춤 이름이 반영되지 않던 문제 해결
2. 사용자가 알림 시간을 변경하면 새롭게 예약되도록 수정
3. 불필요한 알림 중복 예약 방지

이제 앱을 실행하면 설정한 이름과 시간이 정상적으로 알림에 반영된다.

profile
iOS 좋아. swift 좋아.

0개의 댓글

관련 채용 정보