昨天已經把 APNs Key 拿到了!今天就是要教大家怎麼修改自己專案的 Code 並進行推播測試!
我們在 App 啟動時,需要去註冊遠端推播,所以我們需要在 AppDelegate > application (didFinishLaunchingWithOptions) 做設定
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("允許")
} else {
print("不允許")
}
})
// 註冊遠程通知
application.registerForRemoteNotifications()
// 給代理到後面的 UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().delegate = self
return true
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// 將Data轉成String
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("deviceTokenString: \(deviceTokenString)")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
return [.banner, .badge, .sound]
}
}