PHP 代码如何将 APNS 设备令牌用于 Apple 推送通知?
Posted
技术标签:
【中文标题】PHP 代码如何将 APNS 设备令牌用于 Apple 推送通知?【英文标题】:How can PHP code use an APNS device token for Apple Push Notification? 【发布时间】:2018-04-04 00:27:21 【问题描述】:我在这里查看 php 代码:
https://gist.github.com/valfer/18e1052bd4b160fed86e6cbb426bb9fc
看起来不错。我很想用它。但我对此感到困惑:
* @param $token the token of the device
所以我需要设备令牌?对于将在服务器上运行的 PHP 代码?如何获取设备令牌?
【问题讨论】:
【参考方案1】:当 ios 应用程序启动时,它会使用您的AppDelegate
的didFinishLaunchingWithOptions
中的以下代码为自己注册 Apple 推送通知。
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
else
//register to receive notifications
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
然后可以根据成功或失败调用以下委托方法
-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
NSString* strdeviceToken = [[NSString alloc]init];
strdeviceToken=[self stringWithDeviceToken:deviceToken];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:strdeviceToken forKey:PREF_DEVICE_TOKEN];
[prefs synchronize];
NSLog(@"My token is===========> : %@",strdeviceToken);
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
// NSLog(@"Failed to get token, error: %@", error);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"" forKey:PREF_DEVICE_TOKEN];
[prefs synchronize];
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
if (application.applicationState == UIApplicationStateActive)
// [self showToastMessage:@"Active"];
else if (application.applicationState == UIApplicationStateBackground)
// [self showToastMessage:@"Background"];
else if (application.applicationState == UIApplicationStateInactive)
// [self showToastMessage:@"Inactive"];
// [self handleIncomingNotification:userInfo delay:0.0];
上述所有逻辑都应在您项目的AppDelegate
类中处理。然后,您可以在您的 PHP 代码中进行一些 API 调用,以便从 iOS 调用,并将此设备令牌发送到您的服务器上并保存以供将来使用。
【讨论】:
不要使用-[NSUserDefaults synchronize]
。来自Apple's documentation“这个方法是不必要的,不应该使用。”以上是关于PHP 代码如何将 APNS 设备令牌用于 Apple 推送通知?的主要内容,如果未能解决你的问题,请参考以下文章