앱에서 로컬 알림을 예약할 때, 사용자 맞춤 이름을 포함해 "소소한 행복을 적어 [이름]를 키워주세요."
라는 메시지를 띄우려고 했다. 하지만 기본값 "행담이"
만 출력되었고, UserDefaults
에서 저장한 사용자 이름이 반영되지 않았다.
또한, 사용자가 알림 시간을 변경하면 기존 예약을 취소하고 새로운 시간을 설정해야 했다.
이름과 알림 시간을 저장하고, 가져오는 코드를 추가했다.
let name = UserDefaults.standard.string(forKey: "name") ?? "행담이"
이를 통해 UserDefaults
에 저장된 값이 없다면 기본값 "행담이"
를 사용하도록 했다.
기존에는 알림을 예약할 때 name
을 직접 하드코딩했지만, UserDefaults
에서 값을 불러와 반영하도록 수정했다.
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)
}
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)
}
}
사용자가 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)")
}
}
}
}
}
기존에는 하드코딩된 값이 사용되었지만, UserDefaults
에서 값을 즉시 가져와 사용하면서 최신 데이터를 반영할 수 있게 되었다.
이를 통해 다음과 같은 문제를 해결했다.
1. 사용자 맞춤 이름이 반영되지 않던 문제 해결
2. 사용자가 알림 시간을 변경하면 새롭게 예약되도록 수정
3. 불필요한 알림 중복 예약 방지
이제 앱을 실행하면 설정한 이름과 시간이 정상적으로 알림에 반영된다.