带有 Swift 的 Firebase 推送通知在 ios 11.4 中不起作用

Posted

技术标签:

【中文标题】带有 Swift 的 Firebase 推送通知在 ios 11.4 中不起作用【英文标题】:Firebase Push Notifications with Swift not working in ios 11.4 【发布时间】:2018-06-29 20:04:42 【问题描述】:

我正在尝试使用 Swift 在 ios 11.4 上使用 Firebase 设置推送通知,但它目前无法正常工作(即,甚至没有出现允许通知的消息)。这是否与我正在为 ios 10 编写代码(这是他们在 Firebase 网站上的内容)这一事实有关,或者此代码是否适用于 ios 10 及更高版本。谁能帮我解决这个问题。非常感谢!

我有以下AppDelegate 代码:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate 

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
    // Override point for customization after application launch.
    FirebaseApp.configure()

    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 )
     else 
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    

    application.registerForRemoteNotifications()

    let token = Messaging.messaging().fcmToken
    print("***** MY FCM token: \(token ?? "")")

    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)


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.
    FBSDKAppEvents.activateApp()


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


func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool 
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)





// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate 

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([.alert, .badge, .sound])


func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) 
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] 
        print("Message ID: \(messageID)")
    

    // Print full message.
    print(userInfo)

    completionHandler()



// [END ios_10_message_handling]

extension AppDelegate : MessagingDelegate 
// [START refresh_token]
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) 
    print("Firebase registration token: \(fcmToken)")

// [END refresh_token]

// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) 
    print("Received data message: \(remoteMessage.appData)")

// [END ios_10_data_message]

以及我的ViewController中的以下内容:

class ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler 

var webView: WKWebView!
let userContentController = WKUserContentController()

override func loadView() 
    super.loadView()

    let preferences = WKPreferences()
    preferences.javascriptEnabled=true

    let configuration = WKWebViewConfiguration()
    configuration.preferences=preferences
    configuration.userContentController=userContentController

    webView = WKWebView(frame: self.view.frame, configuration: configuration)
    //webView = WKWebView(frame: self.view.frame)
    let token = Messaging.messaging().fcmToken

    let userScript = WKUserScript(
        source: "change_me(\"\(token ?? "")\")",
        injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
        forMainFrameOnly: true
    )

    userContentController.addUserScript(userScript)
    webView?.configuration.userContentController.add(self, name: "scriptHandler")
    webView.navigationDelegate=self

    self.view.addSubview(webView!)


public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) 
    print("********Message received: \(message.name) with body: \(message.body)")

    let loginManager = LoginManager()
    loginManager.loginBehavior = LoginBehavior.native
    loginManager.logIn( readPermissions: [ReadPermission.publicProfile], viewController: self)  loginResult in
        switch loginResult 
        case .failed(let error):
            print(error)
        case .cancelled:
            print("User cancelled login.")
        case .success(let grantedPermissions, let declinedPermissions, let accessToken):
            print("Logged in!")
            print("\(accessToken)")
        
    




@IBAction func button(_ sender: UIButton) 

    print("Result: ")


override func viewDidLoad() 
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let taskershopURL = URL(string: "https://www.taskershop.ca")
    let taskershopURLRequest = URLRequest(url:taskershopURL!,cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData)
    webView?.load(taskershopURLRequest)


    let token = Messaging.messaging().fcmToken
    print("-------- FCM token: \(token ?? "")")



override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.




【问题讨论】:

【参考方案1】:

首先确保你有一个付费开发者账户,激活项目功能部分的通知,在苹果会员中心设置所有证书并将此证书添加到 gcm(见How to use Apple's new .p8 certificate for APNs in firebase console),你还必须使用真机

我假设你已经拥有这 3 个 Pod

import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

首先你需要将它添加到 didfinishlaunchingwithoptions

FirebaseApp.configure()
Messaging.messaging().delegate = self
registerForPushNotifications()

然后添加这两个func来获取用户权限

func getNotificationSettings() 
    if #available(iOS 10.0, *) 
        UNUserNotificationCenter.current().getNotificationSettings  (settings) in
            guard settings.authorizationStatus == .authorized else  return 
            DispatchQueue.main.async(execute: 
                UIApplication.shared.registerForRemoteNotifications()
            )
        
     else 
        // Fallback on earlier versions
    


func registerForPushNotifications() 
    if #available(iOS 10.0, *) 
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) 
            (granted, error) in 
            guard granted else  return 
            self.getNotificationSettings()
        
     else 
        let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
        UIApplication.shared.registerForRemoteNotifications()
    

要获取 firebase 令牌,请添加此

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) 
    print(fcmToken)

从现在开始,您应该能够看到权限提示并从 Firebase 控制台推送通知

如果您需要从代码中执行通知,我就是这样做的(确保用您的 firebase api 密钥替换)

func sendPushNotification(notData: [String: Any]) 
    let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("key=YOUR-SERVER-API-KEY", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"

    request.httpBody = try? JSONSerialization.data(withJSONObject: notData, options: [])
    let task = URLSession.shared.dataTask(with: request)  data, response, error in
        guard let data = data, error == nil else 
            print(error ?? "")
            return
        

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200          
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print(response ?? "")
        

        let responseString = String(data: data, encoding: .utf8)
        print(responseString ?? "")
    
    task.resume()

然后在需要的时候调用这个函数

let notifMessage: [String: Any] = [
        "to" : "fcm token you need to send the notification",
        "notification" :
            ["title" : "title you want to display", "body": "content you need to display", "badge" : 1, "sound" : "default"]
    ]

sendPushNotification(notData: notifMessage)

【讨论】:

谢谢它的工作。我错过了一些必需的进口。非常感谢! @AndraAvram 接受这个答案,你也可以投票。 这在后台为您工作吗? didreceive 和 UNNotification 代表是否要求在后台接收推送?请你确认一下。我们在静默推送通知中遇到问题,并且应用在 iOS 11 上没有收到任何委托方法。@R.Mohan 对此有什么帮助吗? 感谢您的回复!但是我们在推送接收(后台模式)上接收 UNNotifications 委托方法时遇到问题。我在 5 天前添加了一个单独的帖子,但问题仍未解决 ***.com/questions/51352652/… 您能否检查一次并回复是否有任何解决方案/纠正我?如果您需要更多详细信息,请告诉我。 @Gopik 你找到解决方案了吗?我面临同样的问题

以上是关于带有 Swift 的 Firebase 推送通知在 ios 11.4 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何从fireBase推送通知swift 4中获取数据

通过 Firebase 函数发送的 Swift 中的加密推送通知

Swift firebase 推送通知无法使用零错误?

使用firebase问题推送通知(ios,swift 4)[关闭]

为啥我在 Swift 中没有收到来自 Firebase 的推送通知?

iOS Swift 使用 Firebase 云消息发送丰富的推送通知