DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Web Push Provisioning: Advancements for Digital Wallet Developers
  • JQueue: A Library to Implement the Outbox Pattern
  • Google Cloud Messaging with Android
  • Send Push Notifications to Users of Another App

Trending

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • Getting Started With Prometheus Workshop: Instrumenting Applications
  • AI for Web Devs: Project Introduction and Setup
  • Microservices With Apache Camel and Quarkus (Part 5)
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Ionic Push Example Supporting State Changes

Ionic Push Example Supporting State Changes

Raymond Camden user avatar by
Raymond Camden
·
Jul. 09, 15 · Tutorial
Like (0)
Save
Tweet
Share
2.36K Views

Join the DZone community and get the full member experience.

Join For Free

please note that i’m writing this blog post while ionic push is still in alpha. everything i discuss here may change before 1.0 is released. use the following code with caution. one of the more interesting features of ionic’s push feature is the ability to recognize a push message with state data. you can craft a push packet that not only includes a state value but state params as well. this is discussed in the faq :

i want my app to open to a specific state when i receive a notification.
in addition to handling this in the onnotification function described here, you can specify which $state a notification should open your app to using the push payload. below is an example json object highlighting this.

{
  "tokens":["1f0ab62df8b5c672653dea8b01d1bab4dc1b15da93f99216b5ba0f621692a89f"],
  "notification": {
    "alert": "basic push!",
    "ios":{
      "priority": 10,
      "badge":2,
      "payload":{ "$state": "about", "$stateparams": "{\"id\": 1}" }
    }
  }
}

this works well, but i ran into a few gotchas while playing with it so i thought i’d write up a quick demo of it to help others. for my demo, i created a new ionic project using the tabs default. i then followed the directions in the quick start to get push setup. one thing that may trip you up right away is that you have to ensure your application always runs the push registration call. the quick start guide has you build a demo where registration is only run when a button is pushed. in some cases, that may make sense. you may not always want to register for push notifications. most likely though you will. so to start off, here is my modified run() block from app.js that includes push registration.

.run(function($ionicplatform, $ionicpush, $state) {
  $ionicplatform.ready(function() {
    // hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.keyboard) {
      cordova.plugins.keyboard.hidekeyboardaccessorybar(true);
    }
    if (window.statusbar) {
      // org.apache.cordova.statusbar required
      statusbar.stylelightcontent();
    }

    $ionicpush.register({
        canshowalert: false, //can pushes show an alert on your screen?
        cansetbadge: true, //can pushes update app icon badges?
        canplaysound: true, //can notifications play a sound?
        canrunactionsonwake: true, //can run actions outside the app,
        onnotification: function(notification) {
          // handle new push notifications here
          console.log(notification);

          return true;
        }
      });


  });
})

i also want to point out two important settings. first, you probably want canshowalert to be false. if not, then every notification will fire an alert in your app. most likely your app will respond to notifications in different ways. sometimes with dialogs, sometimes not, but probably not always one way or the other. secondly, to actually enable “respond to state so and so”, you want to set canrunactionsonwake to true.

cool – so almost there. i then create a push notification via curl that included the state info. the tags application includes a state called tags.chat, so i decided to use that as my ‘target':

curl -u appkeythingy: -h "content-type: application/json" -h "x-ionic-application-id: 6aef0d7b" https://push.ionic.io/api/v1/push -d '{"tokens": ["a device token"],"notification":{"alert":"ray","ios":{"payload":{"$state":"tab.chats"}}}}'

you want to be careful when crafting the json of your notification. the server is pretty good about noticing mistakes, but on more than one occasion i screwed that part up. note that you include the state information in the payload section. also note that i didn’t bother sending state params either.

so… this worked! and it was cool! then i tested again and it failed. sad kitty. why? did you notice the preference back there in register was canrunactionsonwake ? specifically – “onwake”. so this feature only works automatically if the application is woken up – not if it is active.

if you think about it, that makes sense. as a user, i don’t want the app automatically shifting focus when a notification comes in. however, you may be curious as to how you could possibly handle this. i modified my notification handler to add in some new logic – just for this:

onnotification: function(notification) {
      // handle new push notifications here
      console.log(notification);
      if(notification["$state"]) {
        //prompt the user to switch
        navigator.notification.confirm("you have a new chat - go to it?", function(btn) {
          if(btn === 1) {
            $state.go(notification["$state"]);
          }
        },"new chat!")
      }
      return true;
}

the modification is simple. i had added the dialogs plugin and then made use of it in my handler. if i see a $state parameter i simply ask the user if they want to view the chats. if they say yes, i switch to it.

now – to be clear – my logic could be a bit tighter. i don’t actually look at the $state value. i should see if it exists and if is tabs.chat, but you get the idea. here it is in action:

shot1

you can grab the full source code here: https://github.com/cfjedimaster/cordova-examples/tree/master/push2 .

push Ionic (mobile app framework)

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Web Push Provisioning: Advancements for Digital Wallet Developers
  • JQueue: A Library to Implement the Outbox Pattern
  • Google Cloud Messaging with Android
  • Send Push Notifications to Users of Another App

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: