在iOS模拟器上测试push

Xcode 11.4通过新家的simctl命令来使我们可以在模拟器上测试推送

启用推送权限

首先需要确保已经有了在iOS模拟器上接收通知的权限

 let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { granted, error in
    // If `granted` is `true`, you're good to go!
}

这只是普通的通知权限

从终端向iOS模拟器发送通知

最简单的测试通知的方法是使用Poes 它适合一个简单地命令行工具,在新的simctl push命令做了一层封装

使用Mint命令进行安装

mint install AvdLee/Poes

在安装成功后,就可以简单使用以下方法发送通知

$ poes send --bundle-identifier com.wetransfer.app --verbose
Generated payload:

{
  "aps" : {
    "alert" : {
      "title" : "Default title",
      "body" : "Default body"
    },
    "mutable-content" : false
  }
}

Sending push notification...
Push notification sent successfully

这避免了创建Json文件的麻烦,并允许在测试app的推送通知时 快速进行迭代
Poes使用xcrun simctl push命令,并添加一层封装 可以根据参数正确生成Json文件

为了理解Poes到底做了什么 我们使用没有Poes情况下测试通知

使用Xcode命令行工具 从终端上使用模拟器

Xcode command-line工具 允许从终端使用模拟器。可以启动模拟器、触发universal link等。 其中就有允许将推送发到iOS模拟器

$ xcrun simctl push --help
Send a simulated push notification
Usage: simctl push <device> [<bundle identifier>] (<json file> | -)

    bundle identifier
         The bundle identifier of the target application
         If the payload file contains a 'Simulator Target Bundle' top-level key this parameter may be omitted.
         If both are provided this argument will override the value from the payload.
    json file
         Path to a JSON payload or '-' to read from stdin. The payload must:
           - Contain an object at the top level.
           - Contain an 'aps' key with valid Apple Push Notification values.
           - Be 4096 bytes or less.

Only application remote push notifications are supported. VoIP, Complication, File Provider, and other types are not supported.

可以看到需要以下参数

  • device
    将其设置为booted可以使用已经打开的模拟器
    当然也可以使用xcrun simctl list devices | grep Booted命令获取设备的标识符
  • bundle identifier
    设置为要测试推送通知的应用程序的标识符
  • json file
    指向包含推送详细信息的Json文件 你也可以使用stdin提供JSON内容

例如

$ xcrun simctl push booted com.wetransfer.app payload.json 
Notification sent to 'com.wetransfer.app'

其JSON文件内容为

{
    "aps": {
        "alert": {
            "body": "Gerard added something new - take a look",
            "title": "Photos"
        }
    }
}

可以在Apple的官方文档中Creating the Remote Notification Payload.详细了解JSON文件的所有可能内容和结构

使用APNS文件测试push notifications

在iOS模拟器上测试推送通知的另一种方法是将APNS文件拖到iOS模拟器中。
其中APNS文件和上面的JSON文件几乎相同 但是添加了Simulator Target Bundle键 描述了要使用的包标识符

{
    "Simulator Target Bundle": "com.wetransfer.app",
    "aps": {
        "alert": {
            "body": "Gerard added something new - take a look",
            "title": "Photos"
        }
    }
}
将APNS文件添加到共享库中

可以通过将APNS文件添加到存储库中 使用同事可以测试应用程序的常见推送通知。您可以为每种通知类型保存配置。

总结

目前测试通知很容易

  • 使用Poes命令行工具轻松生成JSON有效负载
  • 引用本地JSON有效负载文件
  • 将APNS文件拖到模拟器中

Poes能够很简单快速的测试
而将APNS文件添加到您的存储库后,可以轻松地遍历应用程序的常见推送通知。

通过学习 workflow category page来提升workflow