Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cordova/Phonegap iOS Parse-Push Plugin

I have spent lot of time to find correct cordova plugin for parse push notifications for both Android & iOS platforms.

My requirements are:

  1. To receive parse push notification (in both android & iOS)
  2. Able to store all the incoming push notifications in mobile local storage Sqlite.

I have tried all the below parse push cordova plugins for both Android & iOS platforms.

  1. https://github.com/avivais/phonegap-parse-plugin
  2. https://github.com/taivo/parse-push-plugin
  3. https://github.com/campers/parse-push-plugin
  4. https://github.com/manishiitg/parse-push-plugin

For Android: All the above plugins are working perfectly to fulfill my above mentioned requirements.

For iOS: Only 1st plugin i.e https://github.com/avivais/phonegap-parse-plugin is working. And that too i was not able to save the notifications in local storage sqlite. That means only my 1st requirement is fulfilled but not my 2nd requirement.

All the github pages of remaining plugins (i.e 2nd, 3rd, 4th) states that:

"Please note that I've only worked on the Android aspect of this fork. The iOS side is not yet up to date."

Is there any plugin which will work for both Android & iOS platforms to fulfill my 2 requirements?

(or)

If there is no common plugin for both the platforms, then how can I store the incoming plugins in iOS sqlite?

Please help me. Thanks in advance.

like image 845
Sivakumar Avatar asked May 27 '15 05:05

Sivakumar


2 Answers

I happen to maintain https://github.com/taivo/parse-push-plugin

It looks like you caught my fork at its infancy. I picked it up when the upstream fork seemed stagnant for a while and at that time I was only addressing the Android aspect. Since then I've provided full iOS support. And it works for parse-server as well as the out-going parse.com. I also did one better and made installation just a matter of

cordova add https://github.com/taivo/parse-push-plugin

and writing a few config.xml tags to indicate server url, and app id.

That should take out the big pain of manually messing with Android Manifest, Java, and Objective C when setting up the plugin.

It should now meet or exceed your requirement. To receive push notification and store in sqlite, all you have to do is set an event handler in javascript. Be sure to wrap it with some sort of device ready or platform ready event handler to ensure the plugin has properly loaded.

$ionicPlatform.ready(function(){
    if(window.ParsePushPlugin){
       ParsePushPlugin.on('receivePN', function(pn){
           console.log('yo i got this notif:' + JSON.stringify(pn) );

           //
           // do your sqlite storage here
           //
       });
    }
});
like image 55
lastoneisbearfood Avatar answered Sep 23 '22 09:09

lastoneisbearfood


You just might be interested in the Azure Push Notifications. It combines both Push notification services so you can send messages to both devices from one central point.

I quote:

Notification Hubs A scalable, cross-platform solution for sending push notifications to mobile devices, Notification Hubs works well with Cordova apps. Notification Hubs manages the registrations with each PNS. More important, Notification Hubs lets you create template registrations so you can send messages to all registered devices, regardless of platform, with only a single line of code. You can also use tags to send targeted notifications only to devices with specific registrations. For more information about Notification Hubs, see the Azure Web site at aka.ms/nkn4n4.

Here i have a helper class for registering your device with the pushnotification service. For sending push notifications, you can use an azure portal and send styled push notifications in json format.

var Pushman = {

    Initialize: function (hubConnString, hubName, gcmSenderId, callbackRegistered, callbackUnRegistered, callbackInlineNotification, callbackBackgroundNotification, callbackError) {

        //store connection and callback information on app startup for Push Registration later
        Pushman.HubConnectionString = hubConnString;
        Pushman.HubName = hubName;
        Pushman.GcmSenderId = gcmSenderId;

        //callbacks
        Pushman.RegisteredCallback = callbackRegistered;
        Pushman.UnRegisteredCallback = callbackUnRegistered;
        Pushman.NotificationForegroundCallback = callbackInlineNotification;
        Pushman.NotificationBackgroundCallback = callbackBackgroundNotification;
        Pushman.ErrorCallback = callbackError;

    },

    RegisterForPushNotifications: function (tags) {
        //setup Azure Notification Hub registration
        Pushman.Hub = new WindowsAzure.Messaging.NotificationHub(Pushman.HubName, Pushman.HubConnectionString, Pushman.GcmSenderId);
        Pushman.Hub.registerApplicationAsync(tags).then(Pushman.onRegistered, Pushman.onError);

        //setup PushPlugin registration
        Pushman.Push = window.PushNotification;
        var push;

        //register depending on device being run
        if (device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {

            //android

            push = Pushman.Push.init(
                 { "android": { "senderID": Pushman.GcmSenderId } }
            );
            push.on('registration', Pushman.onRegistered);
            push.on('notification', Pushman.onAndroidNotification);
            push.on('error', Pushman.onError);


        } else {

            //iOS
            push = Pushman.Push.init(
                { "ios": { "alert": "true", "badge": "true", "sound": "true" } }
                );

            push.on('registration', Pushman.onRegistered);
            push.on('notification', Pushman.onIOSNotification);
            push.on('error', Pushman.onError);

        }
    },

    UnRegisterForPushNotifications: function () {

        if (Pushman.Hub != null) {

            //dont pass through error handler

            //unreg azure
            Pushman.Hub.unregisterApplicationAsync()
               .then(Pushman.onUnRegistered, null);

            //unreg native
            Pushman.Push.unregister(Pushman.onUnRegistered, null);

        }

    },

    onRegistered: function (msg) {
        Pushman.log("Registered: " + msg.registrationId);

        //only call callback if registrationId actually set
        if (msg.registrationId.length > 0 && Pushman.RegisteredCallback != null) {
            Pushman.RegisteredCallback(msg);
        }
    },

    onUnRegistered: function () {
        Pushman.log("UnRegistered");

        if (Pushman.UnRegisteredCallback != null) {
            Pushman.UnRegisteredCallback();
        }
    },

    onInlineNotification: function (msg) {
        Pushman.log("OnInlineNotification: " + msg);

        if (Pushman.NotificationForegroundCallback != null) {
            Pushman.NotificationForegroundCallback(msg);
        }
    },

    onBackgroundNotification: function (msg) {
        Pushman.log("OnBackgroundNotification: " + msg);

        if (Pushman.NotificationBackgroundCallback != null) {
            Pushman.NotificationBackgroundCallback(msg);
        }
    },

    onColdStartNotification: function (msg) {
        Pushman.log("OnColdStartNotification: " + msg);

        if (Pushman.NotificationBackgroundCallback != null) {
            Pushman.NotificationBackgroundCallback(msg);
        }
    },

    onError: function (error) {
        Pushman.log("Error: " + error);

        if (Pushman.ErrorCallback != null) {
            Pushman.ErrorCallback(error);
        }
    },

    onAndroidNotification: function (e) {

        switch (e.event) {
            case 'registered':

                if (e.regid.length > 0) {
                    Pushman.onRegistered("Registered");
                }
                break;

            case 'message':

                if (e.foreground) {

                    //if this flag is set, this notification happened while app in foreground
                    Pushman.onInlineNotification(e.payload.message);

                } else {

                    //otherwise app launched because the user touched a notification in the notification tray.
                    if (e.coldstart) {
                        //app was closed
                        Pushman.onColdStartNotification(e.payload.message);
                    }
                    else {
                        //app was minimized
                        Pushman.onBackgroundNotification(e.payload.message);
                    }
                }
                break;

            case 'error':
                Pushman.onError(e.msg);
                break;

            default:
                Pushman.onError("Unknown message");
                break;
        }
    },

    onIOSNotification: function (event) {

        //TODO: not sure how ios works re cold start vs inline msg types?

        if (event.alert) {
            navigator.notification.alert(event.alert);
        }
        if (event.badge) {
            Push.setApplicationIconBadgeNumber(app.successHandler, app.errorHandler, event.badge);
        }
    },

    tokenHandler: function (result) {
        // iOS - not sure its use though appears somewhat important

        // Your iOS push server needs to know the token before it can push to this device
        // here is where you might want to send it the token for later use.
        alert('device token = ' + result);

    },

    log: function (msg) {
        console.log(msg);
    },

}

///"class" variables - not sure how to put them into the js "class"
Pushman.Push = null;
Pushman.Hub = null;
Pushman.HubConnectionString = null;
Pushman.HubName = null;
Pushman.GcmSenderId = null;
Pushman.NotificationForegroundCallback = null;
Pushman.NotificationBackgroundCallback = null;
Pushman.RegisteredCallback = null;
Pushman.UnRegisteredCallback = null;
Pushman.ErrorCallback = null;

I did not write this myself, all credit goes to this guy.

Then you just need to initialize the plugin when the application starts:

//azure notificationshub connection information
notificationHubPath = "notificationhub name";
connectionString = "notificatin hub connectionstring";
//sender id for google cloud services
var senderIdGCM = "sender id from google gcm";
//tag registration (csv string), can be empty but not undefined
var registrationTagsCsv = ""; //test1, test2

var app = {

    Initialize: function () {
        //reg for onload event
        this.AppStart();
    },

    AppStart: function () {
        "use strict";
        document.addEventListener('deviceready', app.onLoad, false);
        document.addEventListener('deviceready', onDeviceReady.bind(this), false);

        function onDeviceReady() {
            // Handle the Cordova pause and resume events
            document.addEventListener('pause', onPause.bind(this), false);
            document.addEventListener('resume', onResume.bind(this), false);

            // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
        };

        function onPause() {
            // TODO: This application has been suspended. Save application state here.
        };

        function onResume() {
            // TODO: This application has been reactivated. Restore application state here.
        };
    },

    onLoad: function () {

        app.log("Initializing...");

        //setup push notifications
        Pushman.Initialize(connectionString, notificationHubPath, senderIdGCM,
                           app.onNotificationRegistered, app.onNotificationUnRegistered,
                           app.onNotificationInline, app.onNotificationBackground, app.onNotificationError);

        //hookup cmd buttons
        app.registerForPush();
        //$("#register").click(app.registerForPush);
        //$("#unregister").click(app.unRegisterForPush);

        app.onAppReady();
    },

    registerForPush: function (a, c) {

        app.log("Registering...");
        //register for tags
        Pushman.RegisterForPushNotifications(registrationTagsCsv);

    },

    unRegisterForPush: function (a, c) {

        app.log("UnRegistering...");
        //register for tags
        Pushman.UnRegisterForPushNotifications();

    },

    onAppReady: function () {
        app.log("Ready");
    },

    onNotificationRegistered: function (msg) {
        app.log("Registered: " + msg.registrationId);
    },

    onNotificationUnRegistered: function () {
        app.log("UnRegistered");
    },

    onNotificationInline: function (data) {
        app.log("Inline Notification: " + data);
    },

    onNotificationBackground: function (data) {
        app.log("Background Notification: " + data);
    },

    onNotificationError: function (error) {
        app.log("Error: " + error);
    },

    log: function (msg) {
        console.log(msg);
    },

};

If you want to store the messages then you just need to add your code for storing to sql where the messages get received. You'll need an azure account to make this work, here you can get a free trail. It will allow you to send up to 1 million push notifications a month free of charge.

like image 40
Chris Avatar answered Sep 22 '22 09:09

Chris