Coder Social home page Coder Social logo

cordova-push-notification's Introduction

Cordova PushNotification Plugin

by Olivier Louvignes

DESCRIPTION

  • This plugin provides a simple way to use Apple Push Notifications (or Remote Notifications) from IOS.

  • This was inspired by the now orphaned ios-phonegap-plugin build by Urban Airship.

PLUGIN SETUP FOR IOS

Using this plugin requires Cordova iOS.

  1. Make sure your Xcode project has been updated for Cordova

  2. Rename the src/ios folder to PushNotification, drag and drop it from Finder to your Plugins folder in XCode, using "Create groups for any added folders"

  3. Add the .js files to your www folder on disk, and add reference(s) to the .js files using <script> tags in your html file(s)

    <script type="text/javascript" src="/js/plugins/PushNotification.js"></script>

  4. Add new entry with key PushNotification and value PushNotification to Plugins in Cordova.plist/Cordova.plist

  5. Make sure your provisioning profiles are set up to support push notifications. Here's a great tutorial.

APPDELEGATE SETUP FOR IOS

This plugin requires modifications to your AppDelegate.h. Append the following line just below other imports.

#import "PushNotification.h"

It also requires modifications to your AppDelegate.m. Append the block below at the end of your file, just before the implementation @end.

/* ... */

/* START BLOCK */

#pragma - PushNotification delegation

- (void)application:(UIApplication*)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    PushNotification* pushHandler = [self.viewController getCommandInstance:@"PushNotification"];
    [pushHandler didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication*)app didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    PushNotification* pushHandler = [self.viewController getCommandInstance:@"PushNotification"];
    [pushHandler didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
    PushNotification* pushHandler = [self.viewController getCommandInstance:@"PushNotification"];
    NSMutableDictionary* mutableUserInfo = [userInfo mutableCopy];

    // Get application state for iOS4.x+ devices, otherwise assume active
    UIApplicationState appState = UIApplicationStateActive;
    if ([application respondsToSelector:@selector(applicationState)]) {
        appState = application.applicationState;
    }

    [mutableUserInfo setValue:@"0" forKey:@"applicationLaunchNotification"];
    if (appState == UIApplicationStateActive) {
        [mutableUserInfo setValue:@"1" forKey:@"applicationStateActive"];
        [pushHandler didReceiveRemoteNotification:mutableUserInfo];
    } else {
        [mutableUserInfo setValue:@"0" forKey:@"applicationStateActive"];
        [mutableUserInfo setValue:[NSNumber numberWithDouble: [[NSDate date] timeIntervalSince1970]] forKey:@"timestamp"];
        [pushHandler.pendingNotifications addObject:mutableUserInfo];
    }
}

/* STOP BLOCK */

@end

In order to support launch notifications (app starting from a remote notification), you have to add the following block inside - (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions, just before the return YES;

[self.window addSubview:self.viewController.view];
[self.window makeKeyAndVisible];

/* START BLOCK */

// PushNotification - Handle launch from a push notification
NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo) {
    PushNotification *pushHandler = [self.viewController getCommandInstance:@"PushNotification"];
    NSMutableDictionary* mutableUserInfo = [userInfo mutableCopy];
    [mutableUserInfo setValue:@"1" forKey:@"applicationLaunchNotification"];
    [mutableUserInfo setValue:@"0" forKey:@"applicationStateActive"];
    [pushHandler.pendingNotifications addObject:mutableUserInfo];
}

/* STOP BLOCK */

return YES;

PLUGIN SETUP FOR ANDROID(@todo)

Using this plugin requires Cordova Android.

  1. Make sure your Android project has been updated for Cordova

  2. Merge both the libs and src folder from this plugin to your projet.

  3. Add the .js files to your assets/www folder on disk, and add reference(s) to the .js files using <script> tags in your html file(s)

    <script type="text/javascript" src="/js/plugins/FacebookConnect.js"></script>

  4. Add new entry with key PushNotification and value org.apache.cordova.plugins.PushNotification to Plugins in res/xml/config.xml

JAVASCRIPT INTERFACE (IOS/ANDROID)

// After device ready, create a local alias
var pushNotification = window.plugins.pushNotification;

registerDevice() does perform registration on Apple Push Notification servers (via user interaction) & retrieve the token that will be used to push remote notifications to this device.

pushNotification.registerDevice({alert:true, badge:true, sound:true}, function(status) {
    // if successful status is an object that looks like this:
    // {"type":"7","pushBadge":"1","pushSound":"1","enabled":"1","deviceToken":"blablahblah","pushAlert":"1"}
    console.warn('registerDevice:%o', status);
    navigator.notification.alert(JSON.stringify(['registerDevice', status]));
});

getPendingNotifications() should be used when your application starts or become active (from the background) to retrieve notifications that have been pushed while the application was inactive or offline. For now, it can only retrieve the notification that the user has interacted with while entering the app. Returned params applicationStateActive & applicationLaunchNotification enables you to filter notifications by type.

pushNotification.getPendingNotifications(function(notifications) {
    console.warn('getPendingNotifications:%o', notifications);
    navigator.notification.alert(JSON.stringify(['getPendingNotifications', notifications]));
});

getRemoteNotificationStatus() does perform registration check for this device.

pushNotification.getRemoteNotificationStatus(function(status) {
    console.warn('getRemoteNotificationStatus:%o', status);
    navigator.notification.alert(JSON.stringify(['getRemoteNotificationStatus', status]));
});

setApplicationIconBadgeNumber() can be used to set the application badge number (that can be updated by a remote push, for instance, resetting it to 0 after notifications have been processed).

pushNotification.setApplicationIconBadgeNumber(12, function(status) {
    console.warn('setApplicationIconBadgeNumber:%o', status);
    navigator.notification.alert(JSON.stringify(['setBadge', status]));
});

getApplicationIconBadgeNumber() get the current value of the application badge number.

pushNotification.getApplicationIconBadgeNumber( function(badgeNumber) {
    console.log('badgeNumber: ' +  badgeNumber);
});

cancelAllLocalNotifications() can be used to clear all notifications from the notification center.

pushNotification.cancelAllLocalNotifications(function() {
    console.warn('cancelAllLocalNotifications');
    navigator.notification.alert(JSON.stringify(['cancelAllLocalNotifications']));
});

getDeviceUniqueIdentifier() can be used to retrieve the original device unique id. (@warning As of today, usage is deprecated and requires explicit consent from the user)

pushNotification.getDeviceUniqueIdentifier(function(uuid) {
    console.warn('getDeviceUniqueIdentifier:%s', uuid);
    navigator.notification.alert(JSON.stringify(['getDeviceUniqueIdentifier', uuid]));
});

Finally, when a remote push notification is received while the application is active, an event will be triggered on the DOM document.

document.addEventListener('push-notification', function(event) {
    console.warn('push-notification!:%o', event);
    navigator.notification.alert(JSON.stringify(['push-notification!', event]));
});
  • Check source for additional configuration.

BUGS AND CONTRIBUTIONS

Patches welcome! Send a pull request. Since this is not a part of Cordova Core (which requires a CLA), this should be easier.

Post issues on Github

The latest code (my fork) will always be here

LICENSE

The MIT License

Copyright (c) 2012 Olivier Louvignes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

CREDITS

Inspired by :

Contributors :

cordova-push-notification's People

Contributors

mgcrea avatar ppcano avatar torre76 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-push-notification's Issues

Detect resume after click in notification

Is it possible to detect when you click in the notification center on the notification you get, when you have the app in background? I need to refresh the page in that case or send the user to a specific section.

Push works in background only

When the push is sent from the server it displays fine when the app is in background or closed (by killing it from the multitasking bar).

When the app is open the push fails to display on the device.

Registering device token iOS7

Hi

I've used your plugin in my phonegap application which I installed on an iOS 6 device. I successfully recieved push notification when I send them to my device token.

Recently I've updated my device to iOS 7, so I've got a new device token that I successfully get when I use the register function in the app.

But when I send push notification to the new device token they aren't recieved on the device. So I tried to send a new push notification to the old device token, and that device token seems to work properly.

Do you know what could be wrong with the new device token. Also the device token is not registered on the first run after installation on the iOS 7 device.

badge Management

am working in push notification for an ios app.how to clear the server side badge counter from the client side when a new notification arrives

Display notification in push-notification event

First.. thx a lot for this great code! Everything is working perfect. I would like to know if it is possible to display the notification I get when my app is active in the push-notification event like the ones I get when the app is not active. I mean, with the nice banner and info in the notification center. Ideas?
Ariel

callbackId not found

I need help. I receive an error in PushNotification.m:
Property 'callbackId' not found on object of type 'CDVInvokedUrlCommand *'
and build failed. No idea what's wrong.
I use cordova 1.9 and Xcode 4.5.2

getcommandinstance

the [self.viewController getCommandInstance:@"PluginName"];

returns null.

@interface PluginName : CDVPlugin

Where in the code does it register your instance of the plugin?

PushNotification.h file not found

I have followed all the steps but Xcode gives me an error going "PushNotification.h file not found" in AppDelegate.h. I have already added the file

getPendingNotifications error

I installed the plugin and working with the Notification API. I didn't have experience before, but it seems the getPendingNotification method is not working ( it returns an empty notiification array ) or perhaps i didn't understand something.

I need to implement a getApplicationIconBadgeNumber to get my app logic working. However, i think the API could be extended to get notificationCenterMessagesLength to cover more cases.

Let me know if you want me to create the current PR.

does not work in iphone 3gs

i have pad 1 & iphone 3gs

pad 1 is work very well but i phone 3gs not work

it seems like issue #4

test cordova version 2.2.0 ~ 2.5.0

Badge Number does not reset

Where do I put the pushNotification.setApplicationIconBadgeNumber() in order to reset the badge number. It just keeps incrementing by the value I specify in the push.

When I open the app, the badge visibly is removed from the icon, however when I then send through another push the number has not been reset.

Thanks

There isn't an android version right?

README implied that there was an Android version... except that @todo.
Just want to make sure I wasn't missing something. Checked your other repos etc.

(Thanks for this btw)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.