![](/img/trans.png)
[英]IOS 11 didRegisterForRemoteNotificationsWithDeviceToken not called
[英]application:didRegisterForRemoteNotificationsWithDeviceToken: not called ios 10.3.2
我想開發一個使用推送通知的簡單代碼。 我根據現有的教程(例如link和this)創建證書和配置文件,但是注冊函數application:didRegisterForRemoteNotificationsWithDeviceToken:
根本沒有被調用,因此我無法獲得設備令牌。
我還在xcode的“功能”選項卡中為背景打開了“推送通知”和“遠程通知”。 這是我在AppDelegate.swift
代碼
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
UIApplication.shared.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("APNs device token: \(deviceTokenString)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("APNs registration failed: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
print("Push notification received: \(data)")
}
我正在使用運行iOS 10.3.2的iPhone 5s
請從didFinishLaunchingWithOptions
方法調用registerForNotifications
//MARK:- Methods
func registerForNotifications(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options:[.alert,.sound]) { (granted, error) in
if granted{
UIApplication.shared.registerForRemoteNotifications()
}else{
print("Notification permission denied.")
}
}
} else {
// For ios 9 and below
let type: UIUserNotificationType = [.alert,.sound];
let setting = UIUserNotificationSettings(types: type, categories: nil);
UIApplication.shared.registerUserNotificationSettings(setting);
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "")
print(token)
}
我找不到它為什么沒有被調用的原因,但是當我將測試目標更改為運行iOS 10.3.2的iPhone 7時,它運行良好。
我不確定為什么會這樣,但是更改目標可能會解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.