【问题标题】:Can't send notification to single divice through the Firebase无法通过 Firebase 向单个设备发送通知
【发布时间】:2017-07-14 12:26:30
【问题描述】:

显示不正确的令牌格式((

我正在使用这个令牌:

2017-07-14 15:15:06.247:无法获取 APNS 令牌错误域 = com.firebase.iid 代码 = 1001“(空)” 注册成功!代币:90377a6eef538be30b735eacb0480a406feadeee851597e857b620a6a345da9e

代码:

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate{

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //create the notificationCenter
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })

        // For iOS 10 data message (sent via FCM)
        //FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    FIRApp.configure()
    FIRInstanceID .instanceID().token()
    return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("Registration succeeded! Token: ", token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Registration failed!")
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

// Firebase notification received
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

    let dict = notification.request.content.userInfo["aps"] as! NSDictionary
    let d : [String : Any] = dict["alert"] as! [String : Any]
    let body : String = d["body"] as! String
    let title : String = d["title"] as! String
    print("Title:\(title) + body:\(body)")
    self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here

}

【问题讨论】:

  • 您能否编辑您的帖子以仅包含相关代码?例如,我看到一些空函数可以删除以使帖子简洁

标签: swift3 push-notification token


【解决方案1】:

只需将FIRApp.configure() 放在didFinishLaunchingWithOptions 的第一行即可。

还要检查推送功能是否“开启”且授权有效。包含 Googleservice-Info.plist 文件,并将 .p12 证书上传到 Firebase 控制台中的 AppRecord,

希望你能得到你的解决方案。

【讨论】:

  • 我会仔细检查所有内容...它确实会向设备的所有用户发送消息,但不会向单个设备发送消息。
【解决方案2】:

试试这个,

打开app.xcworkspace文件,选择Target > Capabilities->推送通知、钥匙串共享和后台模式->远程通知

【讨论】:

  • 你能检查你的设备日期吗,因为设备日期必须设置为当前日期。
  • 你这是什么意思? iOS 是最新的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 2020-12-24
  • 2023-03-20
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多