0

我今天和昨天一直在打破我的頭,因爲某些原因,我的iOS應用程序未收到任何Firebase通知。就我所知,我已經盡了一切努力。iOS Firebase消息傳遞沒有收到

  • 我檢查了我的Apple開發人員帳戶中的認證,並且所有設置都正確(請參閱屏幕截圖)。
  • 我是一個物理設備
  • 火力地堡設置正確和日誌顯示它連接到火力正確
  • 我已經啓用推送通知,後臺獲取和遠程通知,在項目的功能選項卡上測試
  • 我已經加入我的APN鑰匙從我的蘋果控制檯火力

當通過火力地堡控制檯發送通知到一個主題或所有iOS應用沒有任何反應。我有相同的應用程序運行在Android平穩的接收所有通知的目標。

AppDelegate.swift

// 
// AppDelegate.swift 
// CoyoteBreda 
// 
// Created by Milan van Dijck on 28/02/2017. 
// Copyright © 2017 Miscoria web development. All rights reserved. 
// 

import UIKit 
import GoogleMaps 
import Firebase 
import FirebaseMessaging 
import UserNotifications 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     // Override point for customization after application launch. 
     GMSServices.provideAPIKey("AIzaSyB2JNmY2D6q7lYKmJmyeeDXdk-ILEM4q1Q") 
     UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) 

     //Initialize firebase 
     //FIRApp.configure() 

     do { 
      Network.reachability = try Reachability(hostname: "www.google.com") 
      do { 
       try Network.reachability?.start() 
      } catch let error as Network.Error { 
       print(error) 
      } catch { 
       print(error) 
      } 
     } catch { 
      print(error) 
     } 

     // Add observer for InstanceID token refresh callback. 
     NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), 
                 name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil) 

     return true 
    } 

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { 
     // ----------------------- 
     // FIREBASE MESSAGING 
     // ----------------------- 
     FIRApp.configure() 

     application.registerForRemoteNotifications() 
     requestNotificationAuthorization(application: application) 

     if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] { 
      NSLog("[RemoteNotification] applicationState: \(applicationStateString) didFinishLaunchingWithOptions for iOS9: \(userInfo)") 
      //TODO: Handle background notification 
     } 


     application.registerForRemoteNotifications() 

     return true; 
    } 

    func tokenRefreshNotification(notification: NSNotification) 
    { 
     if let refreshedToken = FIRInstanceID.instanceID().token() 
     { 
      print("InstanceID token: \(refreshedToken)") 
     } 
     // Connect to FCM since connection may have failed when attempted before having a token. 
     connectToFcm() 
    } 

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) 
    { 
     FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.sandbox) 
     FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type: FIRInstanceIDAPNSTokenType.prod) 
    } 

    func connectToFcm() 
    { 
     FIRMessaging.messaging().connect { (error) in 
      if (error != nil) 
      { 
       print("[Unable to connect with FCM. \(String(describing: error))]") 
      } 
      else 
      { 
       print("[Connected to FCM.]") 
      } 
     } 
    } 

    var applicationStateString: String { 
     if UIApplication.shared.applicationState == .active { 
      return "active" 
     } else if UIApplication.shared.applicationState == .background { 
      return "background" 
     }else { 
      return "inactive" 
     } 
    } 

    func requestNotificationAuthorization(application: UIApplication) { 
     if #available(iOS 10.0, *) { 
      UNUserNotificationCenter.current().delegate = self 
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] 
      UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in }) 
     } else { 
      let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
      application.registerUserNotificationSettings(settings) 
     } 
    } 

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
     print("[REGISTERING FOR TOPICS]") 
     FIRMessaging.messaging().subscribe(toTopic: "/topics/activiteit") 
     FIRMessaging.messaging().subscribe(toTopic: "/topics/message") 
    } 

    func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 

     // Update the database 
     DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: completionHandler) 

     // TODO: update views 

     //completionHandler(.newData) 
    } 

    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. 
     connectToFcm() 

     DatabaseUpdater.performUpdate(performFetchWithCompletionHandler: {(result: UIBackgroundFetchResult) -> Void in 
      NSLog("Done updating!") 
     }) 
    } 

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


} 

@available(iOS 10, *) 
extension AppDelegate : FIRMessagingDelegate { 
    // Receive data message on iOS 10 devices. 
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { 
     print("%@", remoteMessage.appData) 
    } 


} 

extension AppDelegate : UNUserNotificationCenterDelegate { 
    // iOS10+, called when presenting notification in foreground 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
     let userInfo = notification.request.content.userInfo 
     NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)") 
     //TODO: Handle foreground notification 
     completionHandler([.alert]) 
    } 

    // iOS10+, called when received response (default open, dismiss or custom action) for a notification 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     let userInfo = response.notification.request.content.userInfo 
     NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) didReceiveResponse: \(userInfo)") 
     //TODO: Handle background notification 
     completionHandler() 
    } 
} 

應用輸出: Application output

蘋果證書:

Provisioning profile

Provisioning profile selection

任何^ h埃爾普將不勝感激。

+0

其中 「FIRInstanceIDAPNSTokenType」 您正在使用?哪些證書?是指開發者還是發行版 –

+0

@VarinderSingh FIRInstanceID.instanceID()。setAPNSToken(deviceToken as Data,type:FIRInstanceIDAPNSTokenType.sandbox)''所以我正在使用'FIRInstanceIDAPNSTokenType.sandbox'我正在使用iOS開發配置文件和iOS開發證書。 – Milan

回答

0

正如您所說,您在Android中收到通知並且遇到了與iOS有關的問題,則可能是由於Payload格式導致此問題。我之前也遇到過這個問題。

請確保您的Payload格式必須如下所示。

{ 
    "aps" : { 
     "alert" : { 
     "body" : "great match!", 
     "title" : "Portugal vs. Denmark", 
     }, 
     "badge" : 1, 
    }, 
    "customKey" : "customValue" 
    } 

如果您的應用在ios 10或更高版本上運行,那麼請確保您設置了delegate

欲瞭解更多信息,請參閱here

+0

我已經嘗試了以下消息:'{ 「數據」:{ 「APS」:{ \t \t 「警告」:{ \t \t 「體」: 「偉大的比賽」, \t \t 「稱號」 :「葡萄牙vs.丹麥」 \t \t}, \t \t 「徽章」:1 \t}, \t 「customKey」: 「customValue」 }, 「要」: 「/主題/消息」 }'但是這仍然沒有按」 t做任何事情,委託在'requestNotificationAuthorization(application:UIApplication)'方法中設置。 – Milan

1

試試這個

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() 

    FirebaseApp.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:. 
} 

// 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 

// print(dict) 

//  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!) 


    completionHandler(.alert) 


} 

@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 


    if response.actionIdentifier == "goToApp"{ 

     let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) 

     let nextViewController = storyBoard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController 
     let appDelegate = UIApplication.shared.delegate as! AppDelegate 
     appDelegate.window?.rootViewController = nextViewController 


    }else if response.actionIdentifier == "cancel" { 

    print("close") 

    }else { 






    } 



    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 

}

+0

試過了,沒有工作 – Milan

相關問題