Swift3 Can';t通过Firebase向单个分区发送通知

Swift3 Can';t通过Firebase向单个分区发送通知,swift3,push-notification,token,Swift3,Push Notification,Token,显示不正确的令牌格式(( 我正在使用这个令牌: 2017-07-14 15:15:06.247:无法获取APNS令牌错误域=com.firebase.iid代码=1001”(空) 注册成功!令牌:90377A6EEF538BE30B735EACB0400A406FEADEE851597E857B620A6A345DA9E 代码: import UIKit import Firebase import FirebaseMessaging import UserNotifications @UIA

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

我正在使用这个令牌:

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

代码:

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

}
导入UIKit
进口火基
导入FirebaseMessaging
导入用户通知
@UIApplicationMain
类AppDelegate:UIResponder、UIApplicationLegate、UNUserNotificationCenterDelegate{
变量窗口:UIWindow?
func应用程序(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptions:[UIApplicationLaunchOptions:任何]?)->Bool{
//应用程序启动后自定义的覆盖点。
//创建通知中心
如果可用(iOS 10.0,*){
//对于iOS 10显示通知(通过APNS发送)
UnuseNotificationCenter.current().delegate=self
let authOptions:UNAuthorizationOptions=[.alert、.badge、.sound]
UnuseNotificationCenter.current().requestAuthorization(
选项:authOptions,
completionHandler:{{{,{in})
//对于iOS 10数据消息(通过FCM发送)
//FIRMessaging.messaging().remoteMessageDelegate=self
}否则{
let设置:UIUserNotificationSettings=
UIUserNotificationSettings(类型:[.alert、.badge、.sound],类别:nil)
application.registerUserNotificationSettings(设置)
}
应用程序.注册表项更改()
FIRApp.configure()
FIRInstanceID.instanceID().token()
返回真值
}
func应用程序(application:UIApplication,DidRegisterForRemotionTificationswithDeviceToken deviceToken:Data){
var token=“”
对于0中的i..Void){
//在应用程序处于前台时处理推送的自定义代码
打印(“从前台处理推送\(notification.request.content.userInfo)”)
让dict=notification.request.content.userInfo[“aps”]as!NSDictionary
设d:[String:Any]=dict[“alert”]as![String:Any]
让body:String=d[“body”]as!String
将title:String=d[“title”]设为!String
打印(“标题:\(标题)+正文:\(正文)”)
self.showAlertAppDelegate(标题:标题,消息:正文,按钮:“确定”,窗口:self.window!)
}
@可用(iOS 10.0,*)
func userNotificationCenter(center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completionHandler:@escaping()->Void){
//如果您在DidReceiveMemoteNotification中设置了一个成员变量,您将知道这是来自closed还是background
打印(“处理后台推送或关闭\(响应.通知.请求.内容.用户信息)”)
}
func showAlertAppDelegate(标题:字符串、消息:字符串、按钮:字符串、窗口:UIWindow){
let alert=UIAlertController(标题:标题,消息:消息,首选样式:UIAlertControllerStyle.alert)
addAction(UIAlertAction(标题:Buttontile,样式:UIAlertActionStyle.default,处理程序:nil))
window.rootViewController?.present(警报、动画:false、完成:nil)
}
//火力基地就在这里结束了
}

只需将
FIRApp.configure()
放在
的第一行,即可使用选项完成启动

另外,检查推送功能是否“开启”,并具有有效权限。包括Googleservice-Info.plist文件,并将.p12证书上载到firebase控制台中的AppRecord

希望您能找到解决方案。

试试这个


打开app.xcworkspace文件,选择目标>功能->推送通知、钥匙链共享和后台模式->远程通知

您是否可以编辑您的帖子,使其仅包含相关代码?例如,我看到一些空函数可以删除,以使post conciseI仔细检查所有内容…它确实会向所有用户发送消息但是,设备的日期不适用于单个设备。您能检查设备日期吗,因为设备日期必须设置为当前日期。这是什么意思?iOS是最新的吗?