从 Xcode 11.4 beta 版本开始支持在 iOS 模拟器上测试推送通知。
准备工作
打开项目的推送通知开关:
截屏2021-10-08 下午4.32.45.png
注册推送通知:
// MARK: - Push Notification
private func setupPushNotification() {
UNUserNotificationCenter.current().delegate = self
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
PushService.instance.receiveDeviceToken(deviceToken: deviceToken)
}
// MARK: - UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if UIApplication.shared.applicationState == UIApplication.State.active {
if let isContract = PushService.instance.isContract(userInfo: notification.request.content.userInfo), !isContract {
if #available(iOS 14.0, *) {
completionHandler([.banner, .list])
} else {
completionHandler([.alert])
}
}
}
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
PushService.instance.check(userInfo: response.notification.request.content.userInfo)
completionHandler()
}
生成 playload 文件:xxx.apns
{
"Simulator Target Bundle": "jp.co.sbisec.sbikabu2spUAT",
"aps": {
"alert": {
"title": "通知 title",
"subtitle": "通知 subtitle",
"body": "通知 message content"
},
"badge": 1,
"sound": "default"
},
"extras": {
"notification_type": "4",
"product_code": "1401",
"index_code": "00"
}
}
注意:xxx.apns文件里extras的格式要与注册通知,接收通知的代码里格式保持一致
使用命令行方式
xcrun simctl push booted xxx.apns
如果出现下面错误:
xcrun: error: unable to find utility "simctl", not a developer tool or in PATH ...
可以通过 Xcode > Preferences > Locations 下的指定命令行工具来解决:
截屏2021-10-08 下午4.50.07.png
如果不想在 playload 文件中指定 app 的 bundle identifier,则可以使用下面命令:
xcrun simctl push booted <app-bundle-identifier> xxx.apns
使用拖拽的方式
直接将 .apns 文件推拽到模拟器中即可,这个是最简单的测试方式