Search code examples
iospush-notificationtitaniumappcelerator

Appcelerator iOS Push notification not working when app is in Foreground


I know about this question. But I think the issue still exist. So my request is to not mark this question as a duplicate.

When iOS app is in Background or not running device receives the notification. But when app is in Foreground, notification is not showing. I am using the same code mentioned in the documentation here

OS: iOS 11.2.5, Phone: iPhone 6 Titanium SDK: 7.0.2.GA

Below is my code for the reference.

exports.createNotification = function() {
if (Ti.UI.iOS.appBadge !== 0) {
    Ti.UI.iOS.appBadge = 0;
}

var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iOS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {

    // Wait for user settings to be registered before registering for push notifications
    Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {

        // Remove event listener once registered for push notifications
        Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);

        Ti.Network.registerUserNotificationSettings({
            success : deviceTokenSuccess,
            error : deviceTokenError,
            callback : receivePush
        });
    });

    // Register notification types to use
    Ti.App.iOS.registerUserNotificationSettings({
        types : [Ti.Network.NOTIFICATION_TYPE_BADGE, Ti.Network.NOTIFICATION_TYPE_ALERT, Ti.Network.NOTIFICATION_TYPE_SOUND]
    });
}

// For iOS 7 and earlier
else {
    Ti.Network.registerForPushNotifications({
        // Specifies which notifications to receive
        types : [Ti.Network.NOTIFICATION_TYPE_BADGE, Ti.Network.NOTIFICATION_TYPE_ALERT, Ti.Network.NOTIFICATION_TYPE_SOUND],
        success : deviceTokenSuccess,
        error : deviceTokenError,
        callback : receivePush
    });
}
// Process incoming push notifications
function receivePush(e) {
    Ti.API.info('Received push: ' + JSON.stringify(e));
    //alert('Received push: ' + JSON.stringify(e));

    if (e.data !== null) {
        //exports.insertPushToDb(e.data);
    }
}

// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {

    deviceToken = e.deviceToken;
    Ti.App.Properties.setString('PushNotificationRegID', deviceToken);
    Ti.API.info('Push notification: ' + deviceToken);
    //alert('deviceToken ' + deviceToken);
}

function deviceTokenError(e) {
    Ti.API.info('Error Noti: '+JSON.stringify(e));
    //alert('Failed to register for push notifications! ' + e.error);
}

};

Thanks in advance.


Solution

  • You have the line that shows the push commented out!

     //alert('Received push: ' + JSON.stringify(e));
    

    Re-enable this line and you’ll see it again.