我想开发一个使用推送通知的简单代码。我根据现有教程创建证书和配置文件,例如link和this,但注册函数application:didRegisterForRemoteNotificationsWithDeviceToken:
根本没有被调用,因此我无法获得设备令牌。
我还在xcode的Capabilities选项卡中启用了Push通知和远程通知。这是我在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
答案 0 :(得分:0)
请从AppDelegate的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)
}
答案 1 :(得分:0)
我找不到为什么没有调用,但是当我将测试目标更改为运行iOS 10.3.2的iPhone 7时,它运行良好。
我不确定为什么会这样,但改变目标可能会解决问题