Push notification is an important feature to engage users frequently, especially when the users are not using the app. Many people download an app but only open it a few times. If you send them a push notification message, it will encourage them to open the app to get involved in a new activity. Implementing push notifications is very complex if you have to build everything from scratch. However, Ionic makes it very simple by leveraging the Cordova Push Notification plugin and Ionic Cloud as the providers. A push notification provider is a server that can communicate with the Apple Push Notification service (APNs) or Google's Firebase Cloud Messaging (FCM). You can set up your own provider server using existing open sources, but you have to maintain this server separately and keep up with potential changes from the APN APIs.
In this section, you will learn how to do the following things:
The following is a screenshot of the app after receiving a couple of notification messages:
It's required to have a physical iOS device available in order to test for notification messages.
You must also register for the Apple Developer Program (ADP) in order to access https://developer.apple.com and https://itunesconnect.apple.com because these websites will require an approved account.
In addition, the following instructions use the specific version of these components:
Observe the following instructions:
MyiOSPush
app using the blank
template, as shown, and go to the MyiOSPush
folder:$ ionic start MyiOSPush blank --v2 $ cd MyiOSPush
cloud-angular
client, which is a library to interact with the push
object, as follows:$ npm install @ionic/cloud-angular --save
$ ionic io init
You will be prompted to log in to your Ionic Cloud account for this command line. The initialization process will save the app_id
and api_key
values to your project's ionic.io.bundle.min.js
. This means you cannot change the project in your Ionic Cloud account after this (or you will have to manually remove the IDs and reinitialize). Your app ID is also recorded in the ionic.config.json
file.
SENDER_ID
. Since you are only using iOS Push Notification, you can just provide a fake value, temporarily, here, as shown in the following code:$ cordova plugin add phonegap-plugin-push --variable SENDER_ID=12341234 --save
./ionic.config.json
file in the project folder and copy the app_id
value. In this case, the value is 00f293c4
from the following code:{ "name": "MyiOSPush", "app_id": "00f293c4", "v2": true, "typescript": true }
./src/app/app.module.ts
with the following content:import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { CloudSettings, CloudModule } from '@ionic/cloud-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; const cloudSettings: CloudSettings = { 'core': { 'app_id': '00f293c4' }, 'push': { 'sender_id': 'SENDER_ID', 'pluginConfig': { 'ios': { 'badge': true, 'sound': true }, 'android': { 'iconColor': '#343434' } } } }; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ IonicModule.forRoot(MyApp), CloudModule.forRoot(cloudSettings) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [] }) export class AppModule {}
MyiOSPush
) to keep things simple, as shown:./config.xml
file or Xcode, as illustrated:CertificateSigningRequest.certSigningRequest
file, as follows:.cer
file you downloaded, as shown, so that it can be imported to Keychain Access:.p12
file format. Ionic Cloud will need this file later in order to generate a push token and send push notifications to the app. Observe the following screenshot:Certificates.p12
file, as illustrated, so that you can import it to Ionic Cloud later:MyiOSPush_Provisioning_Profile.mobileprovision
):MyiOSPush_Provisioning_Profile.mobileprovision
, which you just downloaded, in order to import it into Xcode:MyiOSPush
):CertificateSigningRequest.certSigningRequest
file that you created earlier:aps_certificate.cer
to avoid overwriting to the earlier .cer
file:.cer
file is downloaded, you need to click on it to import it to Keychain Access:.cer
to .p12
file for Ionic Cloud:.p12
file to protect it:MyiOSPush
):MyPushProfile
that you just created to edit the settings:Certificates.p12
(from Step 30) and MyiOSPush_Provisioning_Profile.mobileprovision
(from Step 44). Ensure that you provide the same password that you used to protect the .p12
file earlier:push_Certificates.p12
file (from Step 58). Ensure that you provide the same password that protects this file:./src/pages/home/home.html
and paste the given code:<ion-header> <ion-navbar> <ion-title> Push Notification </ion-title> </ion-navbar> </ion-header> <ion-content padding> <code class="center">{{ pushToken }}</code> <button ion-button block [disabled]="clicked" [hidden]="pushToken" (click)="registerPush()"> <span [hidden]="clicked">Register Push</span> <span [hidden]="!clicked">Registering...</span> </button> <h2 class="big-square" *ngIf="!pushToken"> You have no message </h2> <h3 class="sub-title" *ngIf="pushToken"> Your messages </h3> <ion-card *ngFor="let msg of messages"> <ion-card-header> {{ msg.title }} </ion-card-header> <ion-card-content> {{ msg.text }} </ion-card-content> </ion-card> </ion-content>
home.ts
file, in the same folder, with the following code:import { Component, ApplicationRef } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Push, PushToken } from '@ionic/cloud-angular'; @Component({ templateUrl: 'home.html' }) export class HomePage { public push: any; public pushToken: string; public messages = []; public clicked: Boolean = false; constructor(public navCtrl: NavController, push: Push, private applicationRef: ApplicationRef) { this.push = push; } private processPush(msg, that) { console.log('Push notification message received'); console.log(msg); this.messages.push({ title: msg.title, text: msg.text }) this.applicationRef.tick(); } registerPush() { this.clicked = true; this.push.register().then((t: PushToken) => { return this.push.saveToken(t); }).then((t: PushToken) => { this.push.rx.notification().subscribe(msg => this.processPush(msg, this)); console.log('Token saved:', t.token); this.pushToken = t.token; }, (err) => { alert('Token error'); console.log(err); }); } }
home.scss
, also in the /home
folder, with the given code:.home-page { .center { text-align: center; } h2.big-square { text-align: center; padding: 50px; color: #D91E18; background: #F9BF3B; } h3.sub-title { text-align: center; padding: 10px; color: #446CB3; background: #E4F1FE; } ion-card ion-card-header { padding: 10px 16px; background: #F9690E; color: white; } ion-card ion-card-header + ion-card-content, ion-card .item + ion-card-content { padding-top: 16px; } }
$ ionic run ios --device
At this point, you have completed the push notification setup and coding. The next step is to verify that you receive notifications via the app. Here are the instructions:
mypushprofile
) that you created earlier. Then, click on the Send this Push button:To understand how the entire process works, let's summarize what you have done, as shown in the following section:
push
object available for the app to use. This push
object has been configured with your Ionic Cloud push provider.Now, let's focus on the coding portion itself to understand how this works.
You need to change how the app bootstraps in app.module.ts
. This requires the importing of the provideCloud
and CloudSettings
providers, as shown:
import { provideCloud, CloudSettings } from '@ionic/cloud-angular';
Besides setting the app_id
to match with your project app_id
in Ionic Cloud, you need to specify the push
object with the parameters you want for both iOS and Android, as follows:
const cloudSettings: CloudSettings = { 'core': { 'app_id': '00f293c4' }, 'push': { 'sender_id': 'SENDER_ID', 'pluginConfig': { 'ios': { 'badge': true, 'sound': true }, 'android': { 'iconColor': '#343434' } } } };
Then, inside NgModule
, you need to insert the following line so that Ionic knows that it needs to initialize Ionic Cloud as well:
CloudModule.forRoot(cloudSettings)
In your home.html
template, there is a button to trigger the registration of push notification by calling registerpush()
:
<code class="center">{{ pushToken }}</code> <button ion-button block [disabled]="clicked" [hidden]="pushToken" (click)="registerPush()"> <span [hidden]="clicked">Register Push</span> <span [hidden]="!clicked">Registering...</span> </button>
This registration process must be intervened manually by the user because the user will have to accept permission in the next step. It's not recommended to require the users to accept a push notification request when they open the app right away. The main reason is because they are not familiar with your app and don't know what to expect (that is, whether they will get bombarded with notifications later on).
The messages will be displayed via the messages
object, as shown in the following code:
<ion-card *ngFor="let msg of messages"> <ion-card-header> {{ msg.title }} </ion-card-header> <ion-card-content> {{ msg.text }} </ion-card-content> </ion-card>
Here, each message
item has the title
and text
fields.
In home.ts
, there are two critical imports that you must be aware of: Push
and PushToken
are required to register and receive push notifications. ApplicationRef
will be discussed later as you need to trigger re-render the Angular template manually, as illustrated:
import { Component, ApplicationRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Push, PushToken } from '@ionic/cloud-angular';
The register
Push() method is the key to acquire the PushToken from Ionic Cloud, as shown:
registerPush() {
this.clicked = true;
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
this.push.rx.notification().subscribe(msg => this.processPush(msg, this));
console.log('Token saved:', t.token);
this.pushToken = t.token;
}, (err) => {
alert('Token error');
console.log(err);
});
}
All you need to call is the this.push.register()
function. This will return a PushToken
object as you can see in the following screenshot of the console log:
To receive notifications, you need to subscribe by using the following code:
this.push.rx.notification().subscribe()
This will call processPush()
each time there is a new notification message, as follows:
private processPush(msg, that) { console.log('Push notification message received'); console.log(msg); this.messages.push({ title: msg.title, text: msg.text }) this.applicationRef.tick(); }
When the user receives a push message, this function will append to the messages
array. If you don't call this.applicationRef.tick()
, the UI will not get updated since this process is outside Angular cycle. If you look into the console log, the PushMessage
looks as follows, with the text
and title
fields:
If the user doesn't open the app, you will see that the notification appears in the notification area.
Ionic has its own iOS setup instructions pages, as follows:
The Cordova Push Notification plugin is available directly at https://github.com/phonegap/phonegap-plugin-push.
For more information about the Apple Push Notification service, you can visit the official documentation at https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html.
3.138.125.188