且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-03 14:32:51

首先确保您拥有付费开发者帐户,从项目功能部分激活通知,使用Apple成员中心设置所有证书并将此证书添加到gcm(请参阅如何在firebase控制台中使用Apple的新.p8证书进行APN ),您还必须使用真实设备进行测试

first make sure you have a paid developer account, activate notification from the project capabilities section, set up all the certificate with apple member center and add this certificate to gcm (see this How to use Apple's new .p8 certificate for APNs in firebase console) , you also must test with a real device

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

I assume that you already have these 3 Pods

import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

首先你需要将它添加到didfinishlaunchingwithoptions

first you need to add this to didfinishlaunchingwithoptions

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

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

then add this two func to get the user permission

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令牌添加此

to get the firebase token add this

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

从现在起你应该能够看到权限提示并从Firebase控制台推送通知

from now you should be able to see the permission prompt and to push notification from the Firebase console

如果你需要从代码执行通知我就是这样做(确保更换)使用来自firebase的api密钥)

if you need to perform a notification from code here is what I do (make sure to replace with your api key from firebase)

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

然后在需要时调用此函数

then call this func when you need

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)