Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions EATSSU/App/Resources/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,10 @@

// MARK: - Notification

/// 🤔 오늘 밥 뭐 먹지…
"notification.dailyWeekdayNotificationTitle" = "🤔 What should I eat today…";
/// 오늘의 학식을 확인해보세요!
"notification.dailyWeekdayNotificationBody" = "Check today's cafeteria menu!";
/// 알림 권한 필요
"notification_error_permission_denied_message" = "Notification Permission Required";
/// 알림을 받으려면 알림 권한을 활성화해야 합니다.\n설정에서 알림 권한을 허용해주세요.
Expand Down
4 changes: 4 additions & 0 deletions EATSSU/App/Resources/ja.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,10 @@

// MARK: - Notification

/// 🤔 오늘 밥 뭐 먹지…
"notification.dailyWeekdayNotificationTitle" = "🤔 今日何を食べよう…";
/// 오늘의 학식을 확인해보세요!
"notification.dailyWeekdayNotificationBody" = "今日の学食メニューをチェックしましょう!";
/// 알림 권한 필요
"notification_error_permission_denied_message" = "通知権限が必要です";
/// 알림을 받으려면 알림 권한을 활성화해야 합니다.\n설정에서 알림 권한을 허용해주세요.
Expand Down
4 changes: 4 additions & 0 deletions EATSSU/App/Resources/ko.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,10 @@

// MARK: - Notification

/// 🤔 오늘 밥 뭐 먹지…
"notification.dailyWeekdayNotificationTitle" = "🤔 오늘 밥 뭐 먹지…";
/// 오늘의 학식을 확인해보세요!
"notification.dailyWeekdayNotificationBody" = "오늘의 학식을 확인해보세요!";
/// 알림 권한 필요
"notification_error_permission_denied_message" = "알림 권한 필요";
/// 알림을 받으려면 알림 권한을 활성화해야 합니다.\n설정에서 알림 권한을 허용해주세요.
Expand Down
4 changes: 4 additions & 0 deletions EATSSU/App/Resources/vi.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,10 @@

// MARK: - Notification

/// 🤔 오늘 밥 뭐 먹지…
"notification.dailyWeekdayNotificationTitle" = "🤔 Hôm nay ăn gì đây…";
/// 오늘의 학식을 확인해보세요!
"notification.dailyWeekdayNotificationBody" = "Xem thực đơn nhà ăn hôm nay!";
/// 알림 권한 필요
"notification_error_permission_denied_message" = "Cần quyền thông báo";
/// 알림을 받으려면 알림 권한을 활성화해야 합니다.\n설정에서 알림 권한을 허용해주세요.
Expand Down
114 changes: 114 additions & 0 deletions EATSSU/App/Sources/Notification/DailyMenuNotificationScheduler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
//
// DailyMenuNotificationScheduler.swift
// EATSSU
//
// Created by 황상환 on 11/9/26.
//

import Foundation
import UserNotifications

/// 평일 11시 "오늘 밥 뭐 먹지…" 로컬 알림
///
/// 찜 알림은 서버가 찜한 메뉴가 나온 사용자에게만 푸시로 보내고, 그 외 사용자에게 가는 일반 학식 알림은
/// 서버 범위가 아니어서 앱이 로컬 알림으로 보낸다. "마이페이지 알림 ON + 기기 알림 권한 허용"일 때만 예약하고,
/// 그 외에는 취소한다. 서버 알림함에는 남지 않는다
enum DailyMenuNotificationScheduler {

// MARK: - Constants

/// 알림 식별자 접두사. 요일별로 하나씩 예약한다 (`weekdayNotification-2` … `-6`)
static let identifierPrefix = "weekdayNotification-"

/// 월~금 (`Calendar.weekday`: 1이 일요일)
static let weekdays = [2, 3, 4, 5, 6]

static let hour = 11

/// 당일 찜 알림(서버 푸시)을 받은 날짜(yyyyMMdd). 같은 날 로컬 알림은 띄우지 않는다
static let favoritePushReceivedDayKey = "dailyMenuNotification.favoritePushReceivedDay"

// MARK: - Decision

static func identifier(weekday: Int) -> String {
"\(identifierPrefix)\(weekday)"
}

/// 주어진 시각이 속한 요일의 알림 식별자
static func identifier(for date: Date, calendar: Calendar = .current) -> String {
identifier(weekday: calendar.component(.weekday, from: date))
}

static func isDailyMenuNotification(identifier: String) -> Bool {
identifier.hasPrefix(identifierPrefix)
}

// MARK: - Sync

/// 진행 중인 맞춤 작업. 다음 호출은 이 작업이 끝난 뒤 실행해, 토글을 빠르게 껐다 켜도 예약·취소 순서가 뒤바뀌지 않게 한다
@MainActor private static var syncTask: Task<Void, Never>?

/// 현재 토글·권한 상태(`NotificationManager.isNotificationAllowed`)에 맞게 예약하거나 취소한다
/// 호출 시점: 앱 실행, 알림 권한 결과, 마이페이지 알림 토글 변경, 언어 변경(문구 갱신)
@MainActor
static func sync() {
let previous = syncTask
syncTask = Task {
await previous?.value
if await NotificationManager.shared.isNotificationEnabled() {
await schedule()
} else {
cancel()
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// 월~금 11시에 반복되는 알림을 등록한다. 같은 식별자로 다시 등록하면 덮어쓰므로(언어 변경 등) 취소 없이 호출해도 된다
private static func schedule() async {
let center = UNUserNotificationCenter.current()
for weekday in weekdays {
let content = UNMutableNotificationContent()
content.title = TextLiteral.Notification.dailyWeekdayNotificationTitle
content.body = TextLiteral.Notification.dailyWeekdayNotificationBody
content.sound = .default

var components = DateComponents()
components.weekday = weekday
components.hour = hour
components.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)

let request = UNNotificationRequest(identifier: identifier(weekday: weekday), content: content, trigger: trigger)
do {
try await center.add(request)
} catch {
print("11시 학식 알림 예약 실패: \(error.localizedDescription)")
}
}
}

/// 예약을 지우고, 오늘 이미 떠 있는 알림도 알림 센터에서 내린다
static func cancel() {
let identifiers = weekdays.map(identifier(weekday:))
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: identifiers)
center.removeDeliveredNotifications(withIdentifiers: identifiers)
}

// MARK: - 찜 알림과 중복 제거

/// 찜 알림(서버 푸시)을 받았을 때 호출. 알림의 식단 날짜(`date`) 기준으로 같은 날 이미 떠 있는 로컬 알림을
/// 알림 센터에서 지우고, 아직 안 떴다면 `shouldPresent`가 거르도록 날짜를 기억한다
///
/// 받은 시각이 아니라 알림의 날짜를 써야, 어제 온 푸시를 오늘 눌렀을 때 오늘 로컬 알림까지 거르지 않는다.
/// 앱이 백그라운드에 있고 사용자가 푸시를 누르지 않으면 이 코드가 실행되지 않아 두 알림이 함께 남을 수 있다
static func didReceiveFavoritePush(on date: Date) {
UserDefaults.standard.set(DateFormatter.serverDay.string(from: date), forKey: favoritePushReceivedDayKey)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier(for: date)])
}

/// 앱 사용 중 로컬 알림이 도착했을 때 띄울지. 같은 날 찜 알림을 이미 받았으면 띄우지 않는다
static func shouldPresent(dailyNotificationOn date: Date = Date()) -> Bool {
UserDefaults.standard.string(forKey: favoritePushReceivedDayKey) != DateFormatter.serverDay.string(from: date)
}
}
30 changes: 22 additions & 8 deletions EATSSU/App/Sources/Notification/NotificationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ class NotificationManager {

// MARK: - Methods

/// 이전 버전이 기기에 예약해 둔 평일 11시 로컬 알림을 지운다
///
/// 11시 학식 알림은 서버 푸시(찜 알림 / 일반 학식 알림, 하루 1건)로 옮겨, 업데이트 후에도 로컬 알림이 남아 있으면 중복으로 온다.
func removeLegacyDailyNotifications() {
let identifiers = [2, 3, 4, 5, 6].map { "weekdayNotification-\($0)" }
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
}

/// 앱 실행 시 알림 발송 권한을 요청하는 팝업 호출 메소드
func requestNotificationPermission() async throws -> Bool {
return try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
Expand All @@ -34,6 +26,28 @@ class NotificationManager {
return await UNUserNotificationCenter.current().notificationSettings()
}

/// 알림을 보내도 되는 상태인지: 마이페이지 알림 토글 ON + 기기 알림 권한 허용
/// 서버 푸시 토큰 등록(`PushTokenManager`)과 11시 로컬 알림(`DailyMenuNotificationScheduler`)이 같은 규칙을 쓴다
static func isNotificationAllowed(authorization: UNAuthorizationStatus, isToggleOn: Bool) -> Bool {
guard isToggleOn else { return false }
switch authorization {
case .authorized, .provisional, .ephemeral:
return true
case .denied, .notDetermined:
return false
@unknown default:
return false
}
}

/// 현재 토글·권한 상태로 `isNotificationAllowed`를 판단한다
func isNotificationEnabled() async -> Bool {
let isToggleOn = UserDefaults.standard.bool(forKey: TextLiteral.MyPage.pushNotificationUserSettingKey)
guard isToggleOn else { return false }
let settings = await checkNotificationSetting()
return Self.isNotificationAllowed(authorization: settings.authorizationStatus, isToggleOn: isToggleOn)
}

/// 알림 권한 상태를 확인해 토글의 다음 상태를 반환. 서버 반영은 `PushTokenManager.sync()`가 한다
func handleNotificationToggle(currentState: Bool) async throws -> Bool {
let settings = await checkNotificationSetting()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ enum NotificationPermissionPrompt {
}

/// "알림 허용하기": 미결정이면 시스템 권한 요청, 이미 거부돼 있으면 설정 이동 안내
/// 허용되면 마이페이지 토글을 켜고 서버에 푸시 토큰을 등록한다
/// 허용되면 마이페이지 토글을 켜고, 서버 푸시 토큰 등록과 11시 로컬 알림 예약을 맞춘다
static func requestPermission(on tabBar: CustomTabBarContainerController) {
Task { @MainActor in
let settings = await NotificationManager.shared.checkNotificationSetting()
Expand All @@ -48,11 +48,13 @@ enum NotificationPermissionPrompt {
let granted = (try? await NotificationManager.shared.requestNotificationPermission()) ?? false
UserDefaults.standard.set(granted, forKey: TextLiteral.MyPage.pushNotificationUserSettingKey)
PushTokenManager.shared.sync()
DailyMenuNotificationScheduler.sync()
case .denied:
presentSettingsDialog(on: tabBar)
default:
UserDefaults.standard.set(true, forKey: TextLiteral.MyPage.pushNotificationUserSettingKey)
PushTokenManager.shared.sync()
DailyMenuNotificationScheduler.sync()
}
}
}
Expand Down
24 changes: 23 additions & 1 deletion EATSSU/App/Sources/Notification/PushRoute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ struct PushRoute {
/// 알림함 항목 id. 있으면 알림을 누른 시점에 읽음 처리한다 (서버가 알림함을 지원하기 전 푸시에는 없다)
let notificationId: Int?

/// 앱이 직접 만드는 이동 (예: 11시 로컬 알림 → 오늘 학식)
init(date: Date, mealTime: MealTime?, notificationId: Int?) {
self.date = date
self.mealTime = mealTime
self.notificationId = notificationId
}

/// 서버 푸시 data: `type`(MENU_FAVORITE / DAILY_MENU), `date`(yyyyMMdd), `timePart`(찜 알림만), `notificationId`(문자열)
init?(userInfo: [AnyHashable: Any]) {
guard let type = userInfo["type"] as? String,
Expand All @@ -29,7 +36,13 @@ struct PushRoute {
self.notificationId = (userInfo["notificationId"] as? String).flatMap(Int.init)
}

private static let supportedTypes: Set<String> = ["MENU_FAVORITE", "DAILY_MENU"]
private static let favoriteType = "MENU_FAVORITE"
private static let supportedTypes: Set<String> = [favoriteType, "DAILY_MENU"]

/// 찜 알림(서버 푸시)인지. 알림 날짜가 있어야 하므로 해석에 성공한 경우만 true
static func isFavorite(userInfo: [AnyHashable: Any]) -> Bool {
(userInfo["type"] as? String) == favoriteType && PushRoute(userInfo: userInfo) != nil
}
}

/// 알림을 누른 시점에 화면이 준비돼 있지 않을 수 있어(앱 실행 직후 스플래시·로그인 등) 이동할 곳을 보관했다가 적용한다
Expand All @@ -53,6 +66,15 @@ final class PushRouter {
return
}
guard let route = PushRoute(userInfo: userInfo) else { return }
handle(route: route)
}

/// 해석이 끝난 이동을 보관하고, 앱이 활성 상태면 바로 적용한다
func handle(route: PushRoute) {
guard Thread.isMainThread else {
DispatchQueue.main.async { self.handle(route: route) }
return
}
pendingRoute = (route, Date())
if UIApplication.shared.applicationState == .active {
applyPendingRoute()
Expand Down
13 changes: 2 additions & 11 deletions EATSSU/App/Sources/Notification/PushTokenManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,8 @@ final class PushTokenManager {

// MARK: - Private

/// 마이페이지 알림 토글 ON + 기기 알림 권한 허용
/// 마이페이지 알림 토글 ON + 기기 알림 권한 허용 (규칙은 `NotificationManager.isNotificationAllowed`)
private static func isNotificationEnabled() async -> Bool {
guard UserDefaults.standard.bool(forKey: TextLiteral.MyPage.pushNotificationUserSettingKey) else { return false }
let settings = await UNUserNotificationCenter.current().notificationSettings()
switch settings.authorizationStatus {
case .authorized, .provisional, .ephemeral:
return true
case .denied, .notDetermined:
return false
@unknown default:
return false
}
await NotificationManager.shared.isNotificationEnabled()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ final class LanguageSettingViewController: BaseViewController {

AppLanguageManager.shared.changeLanguage(to: language)
ServerLanguageSync.sync(language)
// 예약된 11시 로컬 알림 문구를 새 언어로 다시 등록한다
DailyMenuNotificationScheduler.sync()
didChangeLanguage = true

AnalyticsService.logEvent("change_language", parameters: ["language": language.rawValue])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,8 +379,9 @@ extension MyPageViewController: UITableViewDelegate {
// 스위치 상태 업데이트
self.switchState = newState
self.saveSwitchStateToUserDefaults()
// 서버는 푸시 토큰 등록 여부로 알림 허용을 판단한다 (ON: 등록, OFF: 삭제)
// 서버는 푸시 토큰 등록 여부로 알림 허용을 판단한다 (ON: 등록, OFF: 삭제). 11시 로컬 알림도 함께 맞춘다
PushTokenManager.shared.sync()
DailyMenuNotificationScheduler.sync()

// UI 업데이트
if let cell = self.mypageView.myPageTableView.cellForRow(at: indexPath) as? NotificationSettingTableViewCell {
Expand Down
33 changes: 26 additions & 7 deletions EATSSU/App/Sources/Utility/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,21 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
// FCM 알림인지 확인
if isFCMNotification(userInfo) {
LaunchSourceManager.shared.setSource(.remoteNotification)
// 학식 알림이면 해당 날짜·시간대의 학식 화면으로 이동. 찜 알림이면 같은 날 11시 로컬 알림은 지운다
if let route = PushRoute(userInfo: userInfo) {
if PushRoute.isFavorite(userInfo: userInfo) {
DailyMenuNotificationScheduler.didReceiveFavoritePush(on: route.date)
}
PushRouter.shared.handle(route: route)
}
} else {
LaunchSourceManager.shared.setSource(.localNotification)
// 11시 로컬 알림은 오늘 학식 화면으로 이동
if DailyMenuNotificationScheduler.isDailyMenuNotification(identifier: notification.request.identifier) {
PushRouter.shared.handle(route: PushRoute(date: Date(), mealTime: nil, notificationId: nil))
}
}

// 학식 알림이면 해당 날짜·시간대의 학식 화면으로 이동
PushRouter.shared.handle(userInfo: userInfo)

completionHandler()
}

Expand Down Expand Up @@ -117,13 +125,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
userInfo["fcm_options"] != nil
}

/// 푸시 알림 권한을 요청하고 설정을 처리합니다.
/// 알림 권한·토글 상태에 맞게 알림 예약과 서버 등록을 맞춥니다.
private func setupNotificationPermissions() {
// 11시 알림은 서버 푸시로 옮겨, 이전 버전이 예약한 로컬 알림은 지운다
NotificationManager.shared.removeLegacyDailyNotifications()
// 시스템 알림 권한은 앱 실행 시 바로 묻지 않는다. 가입 직후 안내 다이얼로그(`NotificationPermissionPrompt`)나
// 마이페이지 토글에서 사용자가 선택했을 때 요청한다
// 권한·토글 상태에 맞게 서버 푸시 토큰 등록/삭제 (로그인 상태일 때만 동작)
// 권한·토글 상태에 맞게 평일 11시 로컬 알림을 예약/취소하고, 서버 푸시 토큰을 등록/삭제한다 (토큰은 로그인 상태일 때만)
DailyMenuNotificationScheduler.sync()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
PushTokenManager.shared.sync()
}

Expand Down Expand Up @@ -210,6 +217,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
extension AppDelegate {
// Foreground에서도 알림이 보이도록 설정
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let request = notification.request
if DailyMenuNotificationScheduler.isDailyMenuNotification(identifier: request.identifier) {
// 11시 로컬 알림: 같은 날 찜 알림을 이미 받았으면 중복이라 띄우지 않는다
guard DailyMenuNotificationScheduler.shouldPresent() else {
completionHandler([])
return
}
} else if PushRoute.isFavorite(userInfo: request.content.userInfo),
let route = PushRoute(userInfo: request.content.userInfo) {
// 찜 알림이 먼저 왔으면 같은 날 11시 로컬 알림은 지우거나 거른다
DailyMenuNotificationScheduler.didReceiveFavoritePush(on: route.date)
}
// 앱 사용 중에 알림이 오면 학식 탭 알림 아이콘에 점을 띄운다
NotificationCenter.default.post(name: .didReceivePushNotification, object: nil)
completionHandler([.banner, .sound, .badge])
Expand Down
3 changes: 3 additions & 0 deletions EATSSU/App/Sources/Utility/Application/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func sceneWillEnterForeground(_ scene: UIScene) {
// 백그라운드에서 포그라운드로 전환 시 필요한 작업 수행
TokenManager.refreshIfNeededAsync()
// 설정 앱에서 알림 권한을 바꾸고 돌아온 경우를 반영해 11시 로컬 알림 예약과 서버 푸시 토큰 등록을 다시 맞춘다
DailyMenuNotificationScheduler.sync()
PushTokenManager.shared.sync()
}

func sceneDidBecomeActive(_ scene: UIScene) {
Expand Down
Loading
Loading