Mihael Isaev

MIT License Swift 6.0 Swift.Stream


简介 👏

这是一个 Swift 库,它提供了通过 Firebase 云消息传递 (Firebase Cloud Messaging) 发送推送通知的功能。

专为 Vapor4 构建,并依赖于 JWT Vapor 库。

💡 Vapor3 版本可在 vapor3 分支和 1.0.0 标签中找到

💡 稳定的 Vapor4 ELF 版本可在 v2 分支和 2.0.0 标签中找到

如果您有改进此软件包的好主意,请在 Vapor 的 Discord 聊天中联系我 (@iMike#3049) 或直接发送 pull request。

希望它对某些人有用 :)

通过 Swift Package Manager 安装 ❤️

编辑您的 Package.swift 文件

//add this repo to dependencies
.package(url: "https://github.com/MihaelIsaev/FCM.git", from: "3.0.0-beta.1")
//and don't forget about targets
.product(name: "FCM", package: "FCM")

它是如何工作的?

首先,您应该在 configure.swift 中配置 FCM。

import FCM

// Called before your application initializes.
func configure(_ app: Application) throws {
    /// case 1
    /// with service account json file
    /// put into your environment variables the following key:
    /// FCM_SERVICE_ACCOUNT_KEY_PATH=path/to/serviceAccountKey.json
    app.fcm.configuration = .envServiceAccountKey
    
    /// case 2
    /// with service account json string
    /// put into your environment variable the following key:
    /// FCM_SERVICE_ACCOUNT_KEY="{"prohect_id": "my_project123",...}"
    app.fcm.configuration = .envServiceAccountKey
    
    /// case 3
    /// put into your environment variables the following keys:
    /// FCM_EMAIL=...          // `client_email` in service.json
    /// FCM_PROJECT_ID=...     // `project_id` in service.json
    /// FCM_PRIVATE_KEY=...    // `private_key` in service.json
    app.fcm.configuration = .envServiceAccountKeyFields

    /// case 4
    /// put into your environment variables the following keys:
    /// FCM_EMAIL=...
    /// FCM_PROJECT_ID=...
    /// FCM_KEY_PATH=path/to/key.pem
    app.fcm.configuration = .envCredentials

    /// case 5
    /// manually
    app.fcm.configuration = .init(email: "...", projectId: "...", key: "...")
}

⚠️ 提示: 您可以从 Firebase 控制台 获取 serviceAccountKey.json

🔑 只需转到设置 -> 服务帐户选项卡,然后在例如 NodeJS 选项卡中按 创建私钥 按钮。

可选:设置默认配置,例如启用通知声音。

将以下代码添加到 app.fcm.configuration = ... 之后的 configure.swift 中。

app.fcm.configuration?.apnsDefaultConfig = FCMApnsConfig(headers: [:], 
                                                         aps: FCMApnsApsObject(sound: "default"))

app.fcm.configuration?.androidDefaultConfig = FCMAndroidConfig(ttl: "86400s",
                                                               restricted_package_name: "com.example.myapp",
                                                               notification: FCMAndroidNotification(sound: "default"))
                                                
app.fcm.configuration?.webpushDefaultConfig = FCMWebpushConfig(headers: [:],
                                                               data: [:],
                                                               notification: [:])

让我们发送第一个推送通知! 🚀

然后,您可以使用令牌、主题或条件发送推送通知。

这是一个使用令牌发送推送通知的示例路由处理程序。

import FCM

func routes(_ app: Application) async throws {
    app.get("testfcm") { req async throws -> String in
        let token = "<YOUR FIREBASE DEVICE TOKEN>" // get it from iOS/Android SDK
        let notification = FCMNotification(title: "Vapor is awesome!", body: "Swift one love! ❤️")
        let message = FCMMessage(token: token, notification: notification)
        let name = try await req.fcm.send(message, on: req.eventLoop)
        return "Just sent: \(name)"
    }
}

fcm.send 返回消息名称,例如 projects/example-3ab5c/messages/1531222329648135

FCMMessage 结构与 Firebase 文档中的 Message 结构完全相同 https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages。因此,您可以查看其源代码以构建正确的消息。

APNS 到 Firebase 令牌转换

您可以从 iOS 应用的依赖项中删除 Firebase 库,因为您可以将纯 APNS 令牌发送到您的服务器,它将自行在 Firebase 中注册。

对于不想将 Firebase 库添加到其应用程序的开发人员来说,这是必须的,尤其是对于使用 Swift Package Manager 的 iOS 项目,因为 Firebase 尚未为其库提供 SPM 支持。

如何使用

准备

  1. 转到 Firebase 控制台 -> 项目设置 -> 云消息传递选项卡
  2. Project Credentials 区域复制 Server Key

下一步是可选的

  1. 将服务器密钥放入环境变量中,例如 FCM_SERVER_KEY=<YOUR_SERVER_KEY>(或将其放入 serviceAccountKey.json 文件中作为 server_key
  2. 将您的应用程序 Bundle Identifier 放入环境变量中,例如 FCM_APP_BUNDLE_ID=<APP_BUNDLE_ID>

令牌注册

/// The simplest way
/// .env here means that FCM_SERVER_KEY and FCM_APP_BUNDLE_ID will be used
let tokens = try await application.fcm.registerAPNS(.env, tokens: "token1", "token3", ..., "token100")
/// `tokens` is array of `APNSToFirebaseToken` structs
/// which contains:
/// registration_token - Firebase token
/// apns_token - APNS token
/// isRegistered - boolean value which indicates if registration was successful

/// instead of .env you could declare your own identifier
extension RegisterAPNSID {
   static var myApp: RegisterAPNSID { .init(appBundleId: "com.myapp") }
}

/// Advanced way
let tokens = try await application.fcm.registerAPNS(
    appBundleId: String, // iOS app bundle identifier
    serverKey: String?, // optional server key, if nil then env variable will be used
    sandbox: Bool, // optional sandbox key, false by default
    tokens: [String]
)
/// the same as in above example

💡 请注意,从 Xcode 调试时获取的推送令牌用于 sandbox,因此请使用 .envSandbox 或不要忘记设置 sandbox: true

贡献者

感谢这些优秀人士的贡献