1

您好,我在iOS 9上收到通知,但没有在安装iOS 10的设备上收到 。可能是什么问题呢?Swift IOS 10 Firebase推送通知

import UIKit 
import CoreData 
import Firebase 
import FirebaseMessaging 
import UserNotifications 


@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate ,FIRMessagingDelegate { 

    public func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { 
     print(remoteMessage.appData) 
    } 

    var window: UIWindow? 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     UINavigationBar.appearance().barTintColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0) 
     //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() 

     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:. 
     // Saves changes in the application's managed object context before the application terminates. 

     if #available(iOS 10.0, *) { 
      self.saveContext() 
     } else { 
      // Fallback on earlier versions 
     } 
    } 



    @available(iOS 10.0, *) 
    lazy var persistentContainer: NSPersistentContainer = { 
     /* 
     The persistent container for the application. This implementation 
     creates and returns a container, having loaded the store for the 
     application to it. This property is optional since there are legitimate 
     error conditions that could cause the creation of the store to fail. 
     */ 
     let container = NSPersistentContainer(name: "IndirimiKovala") 
     container.loadPersistentStores(completionHandler: { (storeDescription, error) in 
      if let error = error as NSError? { 
       // Replace this implementation with code to handle the error appropriately. 
       // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

       /* 
       Typical reasons for an error here include: 
       * The parent directory does not exist, cannot be created, or disallows writing. 
       * The persistent store is not accessible, due to permissions or data protection when the device is locked. 
       * The device is out of space. 
       * The store could not be migrated to the current model version. 
       Check the error message to determine what the actual problem was. 
       */ 
       fatalError("Unresolved error \(error), \(error.userInfo)") 
      } 
     }) 
     return container 
    }() 

    // MARK: - Core Data Saving support 
    @available(iOS 10.0, *) 
    func saveContext() { 
     let context = persistentContainer.viewContext 
     if context.hasChanges { 
      do { 
       try context.save() 
      } catch { 
       // Replace this implementation with code to handle the error appropriately. 
       // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       let nserror = error as NSError 
       fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
      } 
     } 
    } 
    // 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) 
    } 

} 

2017年8月2日00:30:44.172 Indirimi Kovala [8086] [火力地堡/分析] [I-ACS003016]火力地堡分析应用代表 代理被禁用。要手动记录深层链接活动,请在FIRAnalytics + AppDelegate.h中调用 方法。 2017-08-02 00:30:44.295: FIRMessaging库版本1.2.2 2017-08-02 00:30:44.299 Indirimi Kovala [8086:863218] *** - [NSKeyedUnarchiver initForReadingWithData:]:data is NULL 2017-08-02 00:30:44.331 Indirimi Kovala [8086] [Firebase/Analytics] [I-ACS023007] Firebase Analytics v.3700000开始2017年8月2日星期一00:30:44.333 Indirimi Kovala [8086] Firebase/Analytics] [I-ACS023008]要启用 调试日志记录,请设置以下应用程序参数: -FIRAnalyticsDebugEnabled(请参阅)注册失败! 2017-08-02 00:30:44.389 [8086] [Firebase/Analytics] [I-ACS005000]当前链接的AdSupport框架不是 。某些功能将无法正常工作。了解更多 在2017年8月2日00:30:44.402 Indirimi Kovala [8086] [火力地堡/ Analytics(分析)] [I-ACS023012]火力地堡分析启用

回答

0

请执行以下两种方法

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 

} 

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping(UIBackgroundFetchResult) -> Void) { 

    completionHandler(UIBackgroundFetchResult.newData) 
}