Building an iOS app to receive push notifications

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:

  • Set up Ionic Cloud for iOS Push Notification
  • Configure iOS app, certificates (App and Push), and provisioning profile
  • Write code to receive push notifications

The following is a screenshot of the app after receiving a couple of notification messages:

Building an iOS app to receive push notifications

Getting ready

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:

  • Mac OSX El Capitan 10.11.4
  • Xcode 7.3.1
  • Ionic CLI 2.1.8
  • Cordova 6.4.0
  • Node 6.8.1
  • NPM 3.10.8

How to do it...

Observe the following instructions:

  1. Create a new MyiOSPush app using the blank template, as shown, and go to the MyiOSPush folder:
    $ ionic start MyiOSPush blank --v2
    $ cd MyiOSPush
    
  2. Install the Ionic cloud-angular client, which is a library to interact with the push object, as follows:
    $ npm install @ionic/cloud-angular --save
    

    Note

    You need to have Node version 4.x or later and NPM version 3.x or later.

  3. Initialize your Ionic Cloud setting, as illustrated, so that an app ID can be created in your account:
    $ ionic io init
    

    Note

    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.

  4. You need to install the Cordova Push Notification plugin and provide some value as 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
    
  5. Open your ./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
    }
  6. Open and edit ./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 {}

    Note

    You must replace 'app_id': '00f293c4' with your own app ID.

  7. Visit the Apple Developer website at https://developer.apple.com and log in with your credentials.
  8. Click on Certificates, Identifiers & Profiles, as illustrated in the following screenshot:
    How to do it...
  9. Select the correct device platform you are targeting. In this case, it will be iOS, tvOS, watchOS as shown in the following screenshot:
    How to do it...
  10. Navigate to Identifiers > App IDs to create an app ID, as illustrated in the following screenshot:
    How to do it...
  11. Click on the plus(+) button in the top right corner of the screen, as shown in the following screenshot:
    How to do it...
  12. Fill in the form to register your App ID. The Name field could be anything and it's not the same Ionic Cloud's app ID. You can provide the name of your project (that is, MyiOSPush) to keep things simple, as shown:
    How to do it...
  13. The important part that you need to do correctly here is the Bundle ID because it must match your bundle identifier in the ./config.xml file or Xcode, as illustrated:
    How to do it...
  14. To enable push notifications, you need to check the Push Notification service on the following page:
    How to do it...
  15. Select Register, as shown:
    How to do it...
  16. Select Done to complete the step to create App ID, as follows:
    How to do it...
  17. To start with certificate creation, you will need to generate a certificate signing request file locally on your Mac OSX using Keychain Access. Navigate to the Keychain Access top left menu and navigate to Certificate Assistant > Request a Certificate From a Certificate Authority…, as illustrated:
    How to do it...
  18. Enter your User Email Address and Common Name. Leave the CA Email Address field blank and check Saved to disk, as shown:
    How to do it...
  19. Save your CertificateSigningRequest.certSigningRequest file, as follows:
    How to do it...
  20. Navigate to the Apple Developer website and navigate to Certificates > All, as shown:
    How to do it...
  21. Click on the plus button in the top right corner to start creating a certificate, as follows:
    How to do it...
  22. You just have to go through the steps on the website to fill out the necessary information. In this example, you will select the Development version instead of Production, as illustrated:
    How to do it...
  23. Click on the Continue button, as follows, to proceed:
    How to do it...
  24. Click on the Choose File… button, as shown in the following screenshot, to upload your signing request file that you saved earlier:
    How to do it...
  25. Click on the Continue button, as illustrated, to proceed:
    How to do it...
  26. Click on the Download button to download your iOS Development certificate file:
    How to do it...
  27. Click on the .cer file you downloaded, as shown, so that it can be imported to Keychain Access:
    How to do it...
  28. Locate your certificate in Keychain Access because you need to export this to the .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:
    How to do it...
  29. Right click and select Export from the drop-down menu:
    How to do it...
  30. Save your Certificates.p12 file, as illustrated, so that you can import it to Ionic Cloud later:
    How to do it...
  31. As illustrated in the following screenshot, provide a password to protect this file:
    How to do it...

    Note

    You must provide a password in this step although it's optional in Keychain Access. The reason is that Ionic Cloud cannot import a .p12 file without a password.

  32. If you need to push the app to a specific device, you must register the device. Go to Devices > All:
    How to do it...
  33. Click on the plus button:
    How to do it...
  34. Provide the device UDID and save to register the device. Observe the following screenshot:
    How to do it...
  35. You'll need a provisioning profile. Navigate to Provisioning Profiles > All:
    How to do it...
  36. Click on the plus button:
    How to do it...
  37. Select iOS App Development as your provisioning profile since this example is for the development version only:
    How to do it...
  38. Click on the Continue button:
    How to do it...
  39. Select the correct App ID in the drop-down menu and save to finalize your provisioning profile creation:
    How to do it...
  40. Click on the Continue button:
    How to do it...
  41. Select the iOS Development certificate you created earlier, as shown in the following screenshot:
    How to do it...
  42. As illustrated, select at least one device that you want to be able to install the app for testing:
    How to do it...
  43. Provide a Profile Name to your provisioning profile, as shown:
    How to do it...
  44. Click on the Download button to download the provisioning profile file (that is, MyiOSPush_Provisioning_Profile.mobileprovision):
    How to do it...
  45. Click on MyiOSPush_Provisioning_Profile.mobileprovision, which you just downloaded, in order to import it into Xcode:
    How to do it...

    Note

    This step is very important because if you don't import it into Xcode, your app cannot be built successfully. If your app failed to build because of an invalid provisioning profile, it's best to check the provisioning profile status in the Developer console.

  46. To enable the Push Notification feature, you must request a Push Certificate, which is different from the app certificate. Select the App ID that you created earlier (that is, MyiOSPush):
    How to do it...
  47. Click on the Edit button at the bottom of the page:
    How to do it...

    Note

    The Push Notifications must show the Configurable state. Otherwise, your app is not available for Push Notifications.

  48. Click on the Create Certificates... button under the Push Notifications > Development SSL Certificate section:
    How to do it...
  49. You will be taken to a new page to create your CSR file. Click on the Continue button:
    How to do it...
  50. Click on the Choose File... button:
    How to do it...
  51. Locate the CertificateSigningRequest.certSigningRequest file that you created earlier:
    How to do it...

    Note

    You must upload the same, .certSigningRequest file as you did for the app certificate. Otherwise, your app will not receive push notifications and it's very hard to debug.

  52. Click on the Continue button:
    How to do it...
  53. Click on the Download button to download the certificate file. You can name it aps_certificate.cer to avoid overwriting to the earlier .cer file:
    How to do it...
  54. Once your .cer file is downloaded, you need to click on it to import it to Keychain Access:
    How to do it...
  55. Locate the new push services certificate in Keychain Access and select it, as illustrated in the following screenshot:
    How to do it...
  56. Right click on the certificate and select Export:
    How to do it...
  57. Give it a new name to avoid overwriting it to the app certificate. This process is, basically, converting a .cer to .p12 file for Ionic Cloud:
    How to do it...
  58. Provide a password for this .p12 file to protect it:
    How to do it...

    Note

    Password for the .p12 file is required because Ionic Cloud will not import a .p12 file for APN without password.

  59. Once you have completed the setup on the Apple Developer website, you need to upload the provisioning profile and two certificates (app and push) to Ionic Cloud. Navigate to https://apps.ionic.io and log in with your credentials.
  60. Select the app generated for this project (that is, MyiOSPush):
    How to do it...
  61. Navigate to Settings > Certificates:
    How to do it...
  62. Select New Security Profile:
    How to do it...
  63. Provide a Profile Name and click on the Create button to save the profile:
    How to do it...
  64. Select EDIT next to the MyPushProfile that you just created to edit the settings:
    How to do it...
  65. You will need to upload three files: a provisioning profile, and app development certificate for the app itself, and an APN certificate for push notification. Let's start with the app requirements. Click on Choose File under Build Credentials and upload two files: 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:
    How to do it...
  66. Click on Choose File under Push Notification Service and upload the push_Certificates.p12 file (from Step 58). Ensure that you provide the same password that protects this file:
    How to do it...

    Note

    You should not get confused between the two .p12 files as one is for your app and one is for your push notification feature.

  67. Click on the Save button to save your security profile. This completes your Ionic Cloud setup for push notification.
  68. You need to modify your home page code in order to receive notification messages. Open and edit ./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>
  69. Replace the content of the 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);
        });
    
      }  
    }
  70. Replace 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;
      }
    }
  71. Connect your physical iPhone to the Mac via a USB connection.
  72. Ensure that you are in the app folder and build for the iOS platform, as follows:
    $ ionic run ios --device
    

    Note

    You may need to include the --device parameter at the end due to an existing bug with Ionic 2.

  73. The OS will prompt to allow codesign to sign using the iOS Developer certificate. You must accept this to allow access in order to build the app and upload it to your device:
    How to do it...
  74. Verify that the app has been running successfully on the device. The initial screen should look as illustrated:
    How to do it...

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:

  1. Click on the Register Push button in the mobile app to register for push notification to the Ionic Cloud provider server to acquire a token. Click on OK to accept permission to receive push notifications, as follows:
    How to do it...
  2. Navigate to Ionic Cloud > your app (MyiOSPush) > Push:
    How to do it...
  3. Click on the CREATE YOUR FIRST PUSH button:
    How to do it...
  4. Fill in the push notification form to create your first push message:
    How to do it...
  5. Verify on the right screen to ensure that the push message is displayed as desired:
    How to do it...
  6. Leave the segment as All users so that anyone can get the push:
    How to do it...
  7. Select the security profile (that is, mypushprofile) that you created earlier. Then, click on the Send this Push button:
    How to do it...
  8. Verify that the push notification has been sent successfully from Ionic Cloud. It should have the Sent status, as shown:
    How to do it...
  9. In the app on your mobile device, verify that the push message has appeared as illustrated:
    How to do it...

You have successfully completed the verification steps.

How it works...

To understand how the entire process works, let's summarize what you have done, as shown in the following section:

  • Created an Ionic project and initialized it to create an Ionic Cloud project:
    • Your Ionic project on the local computer must sync with the Ionic Cloud project for push notifications and other management, such as user authentication
  • Set up your Apple Developer account by doing the following things:
    • Created an app ID
    • Created app certificate (after creating a signing request locally via Keychain Access)
    • Created a provisioning profile
    • Created a push certificate
  • Set up your Ionic Cloud account:
    • Created a security profile.
    • Imported three files from Apple Developer: an app certificate, a provisioning profile, and a push certificate. These files are needed so that Ionic Cloud can be a trusted provider to communicate with Apple's APN server to trigger push notifications.
  • Wrote code in your app to receive notifications:
    • You need to install the Ionic Cloud Angular library and the Cordova Push Notification plugin. The basic idea is to make the 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 registerPush() 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:

How it works...

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:

How it works...

If the user doesn't open the app, you will see that the notification appears in the notification area.

There's more...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.125.188