SwiftUI프로그래밍

[iOS 어플 개발] iOS (Apple Push Notification service, APNs) 기준으로 푸시 알림 인증키 설정 및 .p8 파일 다운로드 방법 (dev, prod)

iOS Push Notification 인증 설정 방법 (APNs)

1. Apple Developer 계정 준비


2. App ID에 Push Notification 활성화

  1. Apple Developer 사이트 → Certificates, Identifiers & ProfilesIdentifiers
  2. 사용 중인 앱 ID 클릭
  3. Push Notifications 기능을 체크하여 활성화
  4. 저장(Save)

3. APNs 인증서 또는 Key 생성

🔹 옵션 1: APNs Auth Key (권장)

  1. Certificates → Keys“+” 버튼
  2. Key 이름 입력 → Apple Push Notifications service (APNs) 체크
  3. Configure 버튼 클릭 -> EnvironmentKey Restriction 선택( 개발, 배포용 따로따로 만드는 것을 추천)
  4. Continue버튼 클릭
  5. 생성(Create) → .p8 파일 다운로드 (한 번만 다운로드 가능)

Environment (환경)
  • Sandbox: 개발 중일 때 사용 (Xcode에서 개발 빌드로 푸시 테스트할 때)
  • Production: 앱이 앱스토어에 올라간 뒤 실제 사용자에게 푸시 보낼 때
  • ✅ 권장: “Production” 선택 (실제 서비스 시 혼란 줄이기 위함) ❗ Sandbox 키는 실제 배포용 앱에서는 사용할 수 없음. 일반적으로 Production 키를 생성해도 개발 빌드에서도 동작함.

Key Restriction
  • Team Scoped (All Topics): 팀의 모든 앱에 푸시 가능 (✅ 대부분 이걸 사용)
  • Topic Scoped: 특정 앱(Bundle ID)에만 푸시 가능 (보안적으로 제한하고 싶을 때)
  • ✅ 권장: Team Scoped (All Topics)
    → 하나의 키로 여러 앱이나 번들에 대해 푸시 보낼 수 있어 유연함

이때 저장해야 할 정보:

  • .p8 파일 (비밀 키)
  • Key ID
  • Team ID (Apple Developer 계정의 팀 ID)

✅ 이 방식은 하나의 키로 여러 앱을 지원 가능하고, 갱신이 필요 없음


🔹 옵션 2: APNs Certificate (구방식)

  1. Certificates → “+” 버튼Apple Push Notification service SSL (Sandbox & Production) 선택
  2. 앱 ID 선택
  3. CSR 파일 업로드 → 인증서 생성 → .cer 파일 다운로드
  4. macOS에서 .cer 파일 더블 클릭 → Keychain에 추가됨
  5. Keychain에서 .p12 형식으로 내보내기 (푸시 서버에서 사용)

✅ 이 방식은 앱마다 인증서를 만들어야 하며, 1년마다 갱신해야 함


4. Xcode 프로젝트 설정

  1. Xcode에서 Signing & Capabilities 탭으로 이동
  2. + CapabilityPush Notifications 추가
  3. 필요시 Background ModesRemote notifications 체크

5. 백엔드 서버에 인증 정보 설정

  • .p8 키 방식:
    • Key ID, Team ID, App Bundle ID, .p8 파일 경로 필요
    • JWT(Json Web Token)을 이용해 APNs에 요청 전송

예시 (Node.js apn 사용):

const apn = require('apn');

let apnProvider = new apn.Provider({
  token: {
    key: "AuthKey_XXXXXX.p8",
    keyId: "YOUR_KEY_ID",
    teamId: "YOUR_TEAM_ID"
  },
  production: false // true for production
});

let notification = new apn.Notification();
notification.alert = "Hello from APNs!";
notification.topic = "com.example.app"; // 앱의 Bundle ID

apnProvider.send(notification, deviceToken).then(response => {
  console.log(response);
});


6. 디바이스에서 Push Token 받기

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
    if granted {
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token: \(token)")
}

🔐 보안 주의

  • .p8 파일은 절대 공개 저장소에 올리면 안 됨.
  • .gitignore에 포함시키고, 서버에만 보관하세요.
AuthKey_*.p8

  • .p8 키는 서버에 안전하게 보관하세요.
  • Sandbox 환경 테스트 시 api.sandbox.push.apple.com을 사용하세요.


.p8 파일 사용 개요

필요한 정보 4가지:

항목설명
.p8 파일Apple Developer에서 받은 비밀 키 파일
Key ID키 생성 시 Apple이 부여한 ID (예: ABC123XYZ9)
Team IDApple Developer 계정의 팀 ID (예: 1A2B3C4D5E)
Bundle ID푸시를 보낼 앱의 Bundle ID (예: com.example.app)

💡 Tip: Team ID 확인 방법

  1. developer.apple.com/account 로그인
  2. 오른쪽 상단에 팀 이름 클릭 → Team ID 확인 가능

🔍 결과 확인

응답 코드의미
200성공
400잘못된 요청
403인증 실패 (토큰/키 문제)
410디바이스 토큰 만료
429요청 너무 많음
500APNs 서버 문제
503일시적 서비스 불가

error: Content is protected !!