I have managed to get push notifications working but I have trouble on how to send notifications to specific users. Perhaps using a customer number or name etc. I don’t know where to even start. I have spent weeks reading hundreds of web sites and I can’t seem to work it out.
These are just a few of the pages I’ve looked at:
- Apple Push Notifications to specific Users
- How to send push notification to specific device
- iOS/Parse – Sending Push Notifications to Specific User
- Send remote push notification to specific user
- Send push notification to specific user?
- https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server?language=objc
- https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns?language=objc
Here is my objective-c code in Appdelegate – Sorry if it’s not great I have pieced it together from several posts.
JavaScript
x
@implementation AppDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSLog( @"for handling push in foreground" );
// Your code
NSLog(@"%@", notification.request.content.userInfo); //for getting response payload data
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionBanner);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UNUserNotificationCenter.currentNotificationCenter.delegate= self;
[self requestPushNotificationPermissions];
NSLog(@"need this:01 @");
return YES;
}
- (void)application:(UIApplication*)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)devToken
{
NSLog(@"need this Token:02 @");
// parse token bytes to string
const char *data = [devToken bytes];
NSMutableString *token = [NSMutableString string];
for (NSUInteger i = 0; i < [devToken length]; i++)
{
[token appendFormat:@"%02.2hhX", data[i]];
}
// print the token in the console.
NSLog(@"Push Notification Token: %@", [token copy]);
}
- (void)requestPushNotificationPermissions
{
// iOS 10+
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus)
{
// User hasn't accepted or rejected permissions yet. This block shows the allow/deny dialog
case UNAuthorizationStatusNotDetermined:
{
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}
}];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if(granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
// [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
// notify user to enable push notification permission in settings
}
}];
break;
}
// the user has denied the permission
case UNAuthorizationStatusDenied:
{
// notify user to enable push notification permission in settings
break;
}
// the user has accepted; Register a PN token
case UNAuthorizationStatusAuthorized:
{
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
// [[UIApplication sharedApplication] registerForRemoteNotifications];
break;
}
default:
break;
}
}];
}
Here is the server side PHP code
JavaScript
<?php
$device_token =
"AB028BLAH8A2BLAHE0485BLAHEABLAHEDFAKED3EBLAHFF0AFDBBBLAHBLAHBLAH";
//echo $key;
$kid = "6FAKEJFAKE";
$teamId = "FAKEZ2FAKE";
$app_bundle_id = "com.name.appname";
$base_url = "https://api.development.push.apple.com";
$header = ["alg" => "ES256", "kid" => $kid];
$header = base64_encode(json_encode($header));
$claim = ["iss" => $teamId, "iat" => time()];
$claim = base64_encode(json_encode($claim));
$token = $header.".".$claim;
// key in same folder as the script
$filename = "AuthKey_6FAKEJFAKE.p8";
$pkey = openssl_pkey_get_private("file://{$filename}");
$signature;
openssl_sign($token, $signature, $pkey, 'sha256');
$sign = base64_encode($signature);
$jws = $token.".".$sign;
$message = '{"aps":{"alert":"Push Test Message.","sound":"default"}}';
function sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws) {
$url = "{$base_url}/3/device/{$device_token}";
// headers
$headers = array(
"apns-topic: {$app_bundle_id}",
'Authorization: bearer ' . $jws
);
// other curl options
curl_setopt_array($curl, array(
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_URL => $url,
CURLOPT_PORT => 443,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $message,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HEADER => 1
));
// go...
$result = curl_exec($curl);
if ($result === FALSE) {
throw new Exception("Curl failed: " . curl_error($curl));
}
print_r($result."n");
// get response
$status = curl_getinfo($curl);
return $status;
}
// open connection
$curl = curl_init();
sendHTTP2Push($curl, $base_url, $app_bundle_id, $message, $device_token, $jws);
?>
This is all working but how to I send it to a specific user?
Advertisement
Answer
You can send push notification to a selected device token.
Before sending follow these steps:
iOS Application side
- On application launch get device token in didRegisterForRemoteNotificationsWithDeviceToken delegate
- Send this token to server using API when user login in the application
Server side
- Store this token in db table corresponding to the user id
- Get device token from db corresponding to the user to whom you want to send notification
- Send notification on that token
- Notification will be received on device