[ios/swiftUI] 파이어베이스를 통한 푸시 알림 다국어 처리

조아·2025년 2월 20일
0

Step1. Notification Service Extension 추가하기

  1. Xcode에서 File > New > Target 선택

  2. Notification Service Extension 검색 후 선택

  3. Product Name을 적절히 지정 (PushNotificationService 등)

  4. Language는 Swift, Include UI Extension은 Off로 설정

  5. 생성 후 Activate 선택

✅ 이제 새로운 타겟이 생기고, NotificationService.swift 파일이 추가됨.

Step2. Localizable 파일 추가하기 (다국어 번역 파일 생성)

1) 최신 방식 (.xcstrings - String Catalog)

Xcode 15부터는 .xcstrings 형식이 권장됨.

String Catalog 방식으로 다국어 추가하기

  1. Xcode에서 File > New > File from Template… 선택

  2. String Catalog (Localizable.xcstrings) 파일 추가

  3. Target Membership에서 PushNotificationService 체크

  4. 기본적으로 Base 언어가 생성됨

  5. + 버튼을 눌러 새로운 키 추가

  • Key → 서버에서 보내는 locKey 값
  • Korean → 한국어 번역 (ko)
  • English → 영어 번역 (en)

👉 현재 본인의 경우, 기본값(디폴트 값)을 한국어(ko)로 설정했기 때문에 다음과 같이 동작함.
• ✅ iOS가 한국어(ko)를 지원하면 → 한국어 값 사용
• ✅ iOS가 한국어(ko)를 지원하지 않으면 → 영어(en) 값 사용
• ❌ 만약 특정 언어의 번역이 없으면 → 키값 자체 (push_notification_order_paid_message)가 표시됨

2) 기존 방식 (Localizable.strings - Strings file)

Localizable.strings는 이전부터 사용되던 방식이지만, 현재는 legacy됨.
하지만 여전히 사용가능함.

  1. Xcode에서 File > New > File from Template… 선택
  2. Strings File 추가 (이름: Localizable.strings)
  3. Target Membership을 PushNotificationService만 체크
  4. Localizable.strings 파일을 언어별로 추가
    • Localizable.strings (English)
    • Localizable.strings (Korean)
    -> 각 파일에 번역을 추가!

Step3. NotificationService.swift 수정 (번역 적용)

//  NotificationService.swift 파일

import UserNotifications

class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        if let bestAttemptContent = bestAttemptContent {
            // userInfo에서 로컬라이제이션 키 가져오기
            if let locKey = bestAttemptContent.userInfo["locKey"] as? String {
                // 현재 시스템 언어 가져오기
              let languageCode = Locale.current.language.languageCode?.identifier ?? "ko"
                
                // 해당 언어에 맞는 번역된 문자열 가져오기
                if let localizedPath = Bundle.main.path(forResource: languageCode, ofType: "lproj"),
                   let localizedBundle = Bundle(path: localizedPath) {
                    let localizedString = NSLocalizedString(locKey, bundle: localizedBundle, comment: "")
                    bestAttemptContent.body = localizedString
                }
            }
            
            contentHandler(bestAttemptContent)
        }
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

Step4. 번역 파일을 익스텐션에서 사용하는 방법

방법 1: Target Membership에서 메인 앱 번들 추가

  1. Xcode에서 Localizable.xcstrings (또는 Localizable.strings) 파일을 선택
  2. 오른쪽 File Inspector에서 Target Membership에서 +클릭
  3. ✅ PushNotificationService(익스텐션)과 앱 번들(메인 앱) 모두 체크

📌 단점
이 방식은 앱의 모든 번역 키-값이 포함되기 때문에, 익스텐션에서 사용하지 않는 불필요한 키까지 추가될 수 있음.

방법 2: 번들 확장 (Extension 번들에서 번역 파일 읽기)

아래처럼 Bundle을 확장해서 익스텐션 번들을 명확하게 지정하기

//  NotificationService.swift 파일
extension Bundle {
    static var notificationExtension: Bundle {
        return Bundle(for: NotificationService.self)
    }
}
//나머지 코드 그대로

📌 이 방식은 불필요한 번역 키가 포함되지 않는 장점이 있지만,
실제 적용했을 때 정상적으로 동작하지 않아 결국 Step4-1 방법으로 진행했다.

Step5. 서버측에서 테스트 푸시 알림 보내기.

Step6. 테스트 방법

📱 1) iPhone에서 언어 변경해서 테스트
1. 설정 > 일반 > 언어 및 지역
2. iPhone 언어를 English (또는 한국어)로 변경

  1. 정상적으로 다국어 처리된 푸시 알림이 뜨는지 확인

🖥️ 2) Xcode에서 강제 언어 설정 후 실행

👉 시뮬레이터에서 특정 언어 강제로 실행하는 방법
1. Xcode 실행 후 Product > Scheme > Edit Scheme
2. Run 탭에서 Arguments Passed On Launch 추가

AppleLanguages (en) 또는 AppleLanguages (ko)

Step7. 추가 체크 사항

✅ Target Membership이 PushNotificationService만 체크되어 있는지 확인
✅ 번역된 문자열이 Localizable.strings 또는 Localizable.xcstrings에 정상적으로 들어갔는지 확인
✅ 푸시 페이로드(userInfo)에서 locKey 값이 정상적으로 넘어오는지 확인
✅ 언어 변경 후에도 번역이 정상 적용되는지 테스트

profile
프론트엔드 개발자

0개의 댓글