Push notifications from device


#1

Hi there

Is there a way for sending push notifications from my app to all the users that have the app installed on the device.

I know from the dashboard (https://apps.ionic.io/apps) where the app is registered on can send the notification to ‘all’ but how do you do this in your code?


#2

+1

I have the same question.

How I can programmatically send a push notification to specific user or to all?


#3

Hi there,

figured it out. Need to send it making a call to api end point.

Example
sendPush(body) { //add bearer token var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NzdiY2QxYi03ZjQ1LTRlNTgtYjlhNC0xMzJhY2Q1MmM2YmUifQ.yv7CvYu3umkExsgLWuJYpTmHD3RbhsWJ7UUUu95H--Q'; var headers = new Headers(); headers.append('Authorization',Bearer ${token}); return this.http.post("https://api.ionic.io/push/notifications" , body, { headers: headers }) .map((response: Response) => response) .catch(this.handleError) }

The body looks like this

body: any = {
"tokens": [],
"send_to_all": false,
"profile": "",
"notification": {
  "message": ""
 }
}

If you set the ‘send_to_all’ to true then this will send the push to all. In my understanding you need to save the device tokens in the data base in order to send the notifications to specific users only.


#4

Hi ariang,

I test your code. I saved the token in the db , then I used it from my other device to send push but I receive 401 UNAUTHORIZED for URL:https://api.ionic.io/push/notifications. I suppose I’ve wrong setting in headers.append(‘Authorization’,Bearer ${token}); row.
I have to use the token of the device in the ${token} parameter?
Thanks for your help.


#5

Hi there

You need to add a bearer token to the header as a means of authorization(different from the device token). The ionic docs provide you with this bearer token that you can get from the dashboard.

This gives quite a bit of info on the apprach.

Hope this helps…let me know if you manage.

regards


Ionic 2 Push Notification In The Client Side
#6

Thank you ariang, It works!
I test among two android devices. in ionic2 rc1.

I have to add also my PROFILE_TAG. (https://apps.ionic.io/apps Settings › Certificates in the Dashboard) to avoid (422) UNPROCESSABLE_ENTITY

body: any = {
"tokens": [<TOKEN_DEVICE_TO_SEND>],
"send_to_all": false,
"profile": "<MYTAG>",
"notification": {
  "message": ""
 }
}

Now I have to test push notification with ios :wink:


#7

Cool, thank man…I still have to get to the IOS


#8

In ios I 'm following the guide http://docs.ionic.io/services/profiles/#ios-push-certificate.


#9

Hi, yes, that would probably be the way but haven’t progressed much further with IOS. I have parked that for now but as soon as I get on the IOS will keep you informed on my progress. In my recollection to publish the app on AppStore one needs the certificate so the same goes for the push notifications.


#10

Hey , would you send me a code section . I’m try this notification but nothings worked i got a lot of error :frowning:


#11

@ibowankenobi
You have to follow this http://docs.ionic.io/services/push/, to generate all the keys and Ids necessary.

Then in your *.ts code:

At the startup of the app you have to register the token of each user and save it on custom db (the example call a php Page http:///indexToken.php):

registerToken(){
    this.push.register().then((t: PushToken) => {
      return this.push.saveToken(t);
    }).then((t: PushToken) => {
      //salvo a db il token
      let variables = 'pushtoken=' + t.token + '&name=' +  this.username;
      let headers = new Headers();
      let serveraddress = 'http://<yourwww>/indexToken.php';
      //content-type
      headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

      /**************************************/
      // don't have the data yet
      new Promise(resolve => {
        this.http.post(serveraddress,variables,{headers:headers})
          .map(
            res => res.json()
          )
          .subscribe(data => {
              alert('Token saved DB: ' + data['ret']);
            },
            err =>{
              alert('error token DB: ' + err);
            });
      });

      alert('Token saved: '+ t.token);
    });
}

Then you can retrieve the tokens of the users from db, I use an auxiliar User class. Then you should be able to send push notification, setting the specific user token in the call.

export class User {
  id: string;
  name:string;
  pushtoken:string;
  constructor(name: string,pushtoken:string) {
    this.pushtoken = pushtoken;
    this.name = name;
  }
}


 sendPushByPhone(event, user) {
    var token = user.pushtoken;
    //PROFILE_TAG The Security Profile tag found in Settings › Certificates in the Dashboard
   // my profile tag is named "prod"
    let body: any = {
      "tokens": [token],
      "send_to_all": false,
      "profile": "prod",
      "notification": {
        "message": "Test From App"
      }
    }

    //generate apitoken https://docs.ionic.io/api/http.html
    var apitoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization','Bearer ' + apitoken);
    return this.http.post("https://api.ionic.io/push/notifications"
      , body, { headers: headers })
      .map((response) => response)
      .subscribe(data => {
        },
        err =>{
          alert('error token DB: ' + err);
        }
      )
  }

Ionic Push Notification Problems
#12

hi, thank you for your example. What can i do if i want to unregister from push notification? What you suggest to do?
For example if i setup a push notification scheduled for 6 months for a specific token and my custom user id saved in the database, if in the meantime the user do the logout (so, i have to unregister from notifications) and login to another device, how can i manage this? The token changes? then i have to update the old scheduled notification? What you suggest?
I hope I was clear