从 Xcode 11.4 beta 版本开始支持在 iOS 模拟器上测试推送通知。
准备工作
打开项目的推送通知开关:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self registerRemoteNotifications];
return YES;
}
- (void)registerRemoteNotifications {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
}
}];
}
生成 playload 文件:
{
"Simulator Target Bundle": "notification.fancy.com.OCDemo",
"aps": {
"alert": {
"title": "模拟器上push",
"subtitle": "测试模拟器push",
"body": "这是一个测试push!"
}
}
}
使用命令行方式
xcrun simctl push booted test_push_notification.apns
如果出现下面错误:
xcrun: error: unable to find utility "simctl", not a developer tool or in PATH ...
可以通过 Xcode > Preferences > Locations 下的指定命令行工具来解决:
如果不想在 playload 文件中指定 app 的 bundle identifier,则可以使用下面命令:
xcrun simctl push booted <app-bundle-identifier> test_push_notification.apns
使用拖拽的方式
这种方式非常简单,直接将 .apns 文件推拽到模拟器中即可.