[iOS] Push通知

実際に「配信」するには サーバー・APNs・証明書 が必要なので複雑

✅ まずは “ローカル通知” の超簡単デモ(その場で動く通知)
プッシュ通知に進む前に、
iOS での 通知許可の取り方・通知の基本 が理解できます。
📌 サンプル:ボタンを押すと10秒後に通知が表示される
NotificationManager.swift

import Foundation
import UserNotifications

class NotificationManager {
    static let shared = NotificationManager()

    // 通知の許可をリクエスト
    func requestPermission() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
            if success {
                print("通知が許可されました")
            } else if let error = error {
                print("通知の許可エラー:", error)
            }
        }
    }

    // ローカル通知をスケジュール
    func scheduleNotification() {
        let content = UNMutableNotificationContent()
        content.title = "テスト通知"
        content.body = "10秒後に届く通知です"
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request)
    }
}
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Text("通知テスト")
                .font(.title)

            Button("通知を許可") {
                NotificationManager.shared.requestPermission()
            }

            Button("10秒後に通知送信") {
                NotificationManager.shared.scheduleNotification()
            }
        }
        .padding()
    }
}

iOSのプッシュ通知の本当の仕組み
あなたのサーバー → APNs(Appleの通知サーバー) → iPhoneに通知

1. アプリが Apple に「通知を受けたい」と登録
→ Apple が端末専用の デバイストークン(Device Token) を発行
→ アプリはこのトークンを サーバー に送る
2. サーバーはそのトークンを使って Apple(APNs) に通知を送る
→ Apple が iPhone にプッシュ通知を配信する

push通知を送る最低限のコード

import SwiftUI
import UserNotifications

@main
struct PushDemoApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    // 起動時に通知登録
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {

        UNUserNotificationCenter.current().delegate = self

        // 通知許可のリクエスト
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }

        return true
    }

    // APNs からデバイストークン取得
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("Device Token:", tokenString)
    }

    // トークン取得失敗時
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to get token:", error.localizedDescription)
    }
}

🔹 このコードでできること
通知許可ダイアログが表示される
トークンが取得できたら Xcode のコンソールに表示される
→ サーバーに送る必要がある

📌 注意
実際のプッシュ通知を送るには、さらに:
🔐 Apple Developer の作業が必要
APNs 証明書 or Key
Push Notifications を有効化
プロビジョニングプロファイル更新

🖥️ サーバー実装も必要(例:Python / Node.js / Firebase など)
APNs に対して HTTPS/JSON で通知を送る