Commit 008a0ec0 by Sebastián Katzer

Update to latest work in progress

parent 58f57589
......@@ -18,8 +18,12 @@
D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E4042BD923824AEB9E9079DC /* QuartzCore.framework */; };
E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = B49413F707024AE39907B73F /* libz.tbd */; };
E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A150CBE2B3E47C5A4319096 /* CDVDevice.m */; };
97FC38A49B614F60924CA868 /* APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = AAE54FB53C834C988F009E8E /* APPLocalNotification.m */; };
F89024F36A5F47C2B8531ACA /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4834642E539E4FB8A4B714D9 /* UserNotifications.framework */; };
26FD3FAAFA0747BC88376EE2 /* APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = 57C74515BDFF4954B31FA9FE /* APPLocalNotification.m */; };
E3D4234280C34B2F9209029E /* APPNotificationContent.m in Sources */ = {isa = PBXBuildFile; fileRef = 802D829FC424419987AC5454 /* APPNotificationContent.m */; };
C357ED37E6D8457FA0E5ED64 /* APPNotificationOptions.m in Sources */ = {isa = PBXBuildFile; fileRef = 6765B471166749439E1FF3A0 /* APPNotificationOptions.m */; };
55F9ABA42267419D873BAB4D /* UNUserNotificationCenter+APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = B8D18131530440E1B637FD25 /* UNUserNotificationCenter+APPLocalNotification.m */; };
D385C624A6A74C06BDA7620C /* UNNotificationRequest+APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = FB24B852192F41FEBD208EC7 /* UNNotificationRequest+APPLocalNotification.m */; };
4B56A07F7C6F40C08671CF74 /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 010B54B769874E79994B98E0 /* UserNotifications.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
......@@ -75,9 +79,17 @@
EB87FDF41871DAF40020F90C /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = ../../config.xml; sourceTree = "<group>"; };
ED33DF2A687741AEAF9F8254 /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bridging-Header.h"; sourceTree = "<group>"; };
F840E1F0165FE0F500CFE078 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = NotificationExample/config.xml; sourceTree = "<group>"; };
AAE54FB53C834C988F009E8E /* APPLocalNotification.m */ = {isa = PBXFileReference; name = "APPLocalNotification.m"; path = "cordova-plugin-local-notifications/APPLocalNotification.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
99F477B096B14D80BDA21DAB /* APPLocalNotification.h */ = {isa = PBXFileReference; name = "APPLocalNotification.h"; path = "cordova-plugin-local-notifications/APPLocalNotification.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
4834642E539E4FB8A4B714D9 /* UserNotifications.framework */ = {isa = PBXFileReference; name = "UserNotifications.framework"; path = "System/Library/Frameworks/UserNotifications.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };
57C74515BDFF4954B31FA9FE /* APPLocalNotification.m */ = {isa = PBXFileReference; name = "APPLocalNotification.m"; path = "cordova-plugin-local-notifications/APPLocalNotification.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
802D829FC424419987AC5454 /* APPNotificationContent.m */ = {isa = PBXFileReference; name = "APPNotificationContent.m"; path = "cordova-plugin-local-notifications/APPNotificationContent.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
6765B471166749439E1FF3A0 /* APPNotificationOptions.m */ = {isa = PBXFileReference; name = "APPNotificationOptions.m"; path = "cordova-plugin-local-notifications/APPNotificationOptions.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
B8D18131530440E1B637FD25 /* UNUserNotificationCenter+APPLocalNotification.m */ = {isa = PBXFileReference; name = "UNUserNotificationCenter+APPLocalNotification.m"; path = "cordova-plugin-local-notifications/UNUserNotificationCenter+APPLocalNotification.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
FB24B852192F41FEBD208EC7 /* UNNotificationRequest+APPLocalNotification.m */ = {isa = PBXFileReference; name = "UNNotificationRequest+APPLocalNotification.m"; path = "cordova-plugin-local-notifications/UNNotificationRequest+APPLocalNotification.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };
116CACCDA264445590A958C1 /* APPLocalNotification.h */ = {isa = PBXFileReference; name = "APPLocalNotification.h"; path = "cordova-plugin-local-notifications/APPLocalNotification.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
70EFDF4472254F8B82B30DA7 /* APPNotificationContent.h */ = {isa = PBXFileReference; name = "APPNotificationContent.h"; path = "cordova-plugin-local-notifications/APPNotificationContent.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
3966B172F40447CAABD975AB /* APPNotificationOptions.h */ = {isa = PBXFileReference; name = "APPNotificationOptions.h"; path = "cordova-plugin-local-notifications/APPNotificationOptions.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
6AD7F7A32D1344B6B7A1C2E2 /* UNUserNotificationCenter+APPLocalNotification.h */ = {isa = PBXFileReference; name = "UNUserNotificationCenter+APPLocalNotification.h"; path = "cordova-plugin-local-notifications/UNUserNotificationCenter+APPLocalNotification.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
1311C4559D3D4CA7864780DE /* UNNotificationRequest+APPLocalNotification.h */ = {isa = PBXFileReference; name = "UNNotificationRequest+APPLocalNotification.h"; path = "cordova-plugin-local-notifications/UNNotificationRequest+APPLocalNotification.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };
010B54B769874E79994B98E0 /* UserNotifications.framework */ = {isa = PBXFileReference; name = "UserNotifications.framework"; path = "System/Library/Frameworks/UserNotifications.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
......@@ -88,7 +100,7 @@
301BF552109A68D80062928A /* libCordova.a in Frameworks */,
E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */,
D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */,
F89024F36A5F47C2B8531ACA /* UserNotifications.framework in Frameworks */,
4B56A07F7C6F40C08671CF74 /* UserNotifications.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
......@@ -161,7 +173,7 @@
children = (
B49413F707024AE39907B73F /* libz.tbd */,
E4042BD923824AEB9E9079DC /* QuartzCore.framework */,
4834642E539E4FB8A4B714D9 /* UserNotifications.framework */,
010B54B769874E79994B98E0 /* UserNotifications.framework */,
);
name = Frameworks;
sourceTree = "<group>";
......@@ -194,8 +206,16 @@
816F86ACE6CD4C8E8FA7A84A /* Toast.m */,
A380129C71E248EDBC5BE744 /* Toast+UIView.h */,
84764C161F33453AB5FD1235 /* Toast.h */,
AAE54FB53C834C988F009E8E /* APPLocalNotification.m */,
99F477B096B14D80BDA21DAB /* APPLocalNotification.h */,
57C74515BDFF4954B31FA9FE /* APPLocalNotification.m */,
802D829FC424419987AC5454 /* APPNotificationContent.m */,
6765B471166749439E1FF3A0 /* APPNotificationOptions.m */,
B8D18131530440E1B637FD25 /* UNUserNotificationCenter+APPLocalNotification.m */,
FB24B852192F41FEBD208EC7 /* UNNotificationRequest+APPLocalNotification.m */,
116CACCDA264445590A958C1 /* APPLocalNotification.h */,
70EFDF4472254F8B82B30DA7 /* APPNotificationContent.h */,
3966B172F40447CAABD975AB /* APPNotificationOptions.h */,
6AD7F7A32D1344B6B7A1C2E2 /* UNUserNotificationCenter+APPLocalNotification.h */,
1311C4559D3D4CA7864780DE /* UNNotificationRequest+APPLocalNotification.h */,
);
name = Plugins;
path = NotificationExample/Plugins;
......@@ -239,6 +259,11 @@
isa = PBXProject;
attributes = {
LastUpgradeCheck = 830;
TargetAttributes = {
1D6058900D05DD3D006BFB54 = {
DevelopmentTeam = V3FHQ5C4T6;
};
};
};
buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "NotificationExample" */;
compatibilityVersion = "Xcode 3.2";
......@@ -321,7 +346,11 @@
E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */,
CA605C2FE84D46FC94CE18B1 /* Toast+UIView.m in Sources */,
91E68846231A433A8F26E364 /* Toast.m in Sources */,
97FC38A49B614F60924CA868 /* APPLocalNotification.m in Sources */,
26FD3FAAFA0747BC88376EE2 /* APPLocalNotification.m in Sources */,
E3D4234280C34B2F9209029E /* APPNotificationContent.m in Sources */,
C357ED37E6D8457FA0E5ED64 /* APPNotificationOptions.m in Sources */,
55F9ABA42267419D873BAB4D /* UNUserNotificationCenter+APPLocalNotification.m in Sources */,
D385C624A6A74C06BDA7620C /* UNNotificationRequest+APPLocalNotification.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
......@@ -346,6 +375,7 @@
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = NO;
DEVELOPMENT_TEAM = V3FHQ5C4T6;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
......@@ -371,6 +401,7 @@
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = YES;
DEVELOPMENT_TEAM = V3FHQ5C4T6;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "NotificationExample/NotificationExample-Prefix.pch";
GCC_THUMB_SUPPORT = NO;
......
......@@ -2,121 +2,141 @@
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small.png",
"scale" : "1x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small@2x.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small@3x.png",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon-40@2x.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon-60@2x.png",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "57x57",
"idiom" : "iphone",
"filename" : "icon.png",
"scale" : "1x"
},
{
"idiom" : "iphone",
"size" : "57x57",
"idiom" : "iphone",
"filename" : "icon@2x.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon-60@2x.png",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon-60@3x.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon-small.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon-small@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon-40.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon-40@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "50x50",
"idiom" : "ipad",
"filename" : "icon-50.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "50x50",
"idiom" : "ipad",
"filename" : "icon-50@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "72x72",
"idiom" : "ipad",
"filename" : "icon-72.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "72x72",
"idiom" : "ipad",
"filename" : "icon-72@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon-76.png",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon-76@2x.png",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon-83.5@2x.png",
"scale" : "2x"
},
......
/*
* Copyright (c) 2013 by appPlant GmbH. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -13,6 +17,8 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import <Cordova/CDVPlugin.h>
......@@ -29,45 +35,45 @@
// Request permission to show notifications
- (void) request:(CDVInvokedUrlCommand*)command;
//// Schedule set of notifications
//- (void) schedule:(CDVInvokedUrlCommand*)command;
// Schedule notifications
- (void) schedule:(CDVInvokedUrlCommand*)command;
//// Update set of notifications
//- (void) update:(CDVInvokedUrlCommand*)command;
//// Cancel set of notifications
//- (void) cancel:(CDVInvokedUrlCommand*)command;
//// Cancel all notifications
//- (void) cancelAll:(CDVInvokedUrlCommand*)command;
//// Clear set of notifications
//- (void) clear:(CDVInvokedUrlCommand*)command;
//// Clear all notifications
//- (void) clearAll:(CDVInvokedUrlCommand*)command;
//
//// If a notification with an ID is present
//- (void) isPresent:(CDVInvokedUrlCommand*)command;
//// If a notification with an ID is scheduled
//- (void) isScheduled:(CDVInvokedUrlCommand*)command;
//// If a notification with an ID is triggered
//- (void) isTriggered:(CDVInvokedUrlCommand*)command;
//
//// List all ids from all local notifications
//- (void) getAllIds:(CDVInvokedUrlCommand*)command;
//// List all ids from all pending notifications
//- (void) getScheduledIds:(CDVInvokedUrlCommand*)command;
//// List all ids from all triggered notifications
//- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command;
//
//// Propertys for given local notification
//- (void) getSingle:(CDVInvokedUrlCommand*)command;
//// Propertya for given scheduled notification
//- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command;
//// Propertys for given triggered notification
//- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command;
//
//// Property list for given local notifications
//- (void) getAll:(CDVInvokedUrlCommand*)command;
//// Property list for given scheduled notifications
//- (void) getScheduled:(CDVInvokedUrlCommand*)command;
//// Property list for given triggered notifications
//- (void) getTriggered:(CDVInvokedUrlCommand*)command;
// Clear notifications by id
- (void) clear:(CDVInvokedUrlCommand*)command;
// Clear all notifications
- (void) clearAll:(CDVInvokedUrlCommand*)command;
// Cancel notifications by id
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is present
- (void) isPresent:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is scheduled
- (void) isScheduled:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is triggered
- (void) isTriggered:(CDVInvokedUrlCommand*)command;
// List of all notification IDs
- (void) ids:(CDVInvokedUrlCommand*)command;
// List of all scheduled notification IDs
- (void) scheduledIds:(CDVInvokedUrlCommand*)command;
// List of all triggered notification IDs
- (void) triggeredIds:(CDVInvokedUrlCommand*)command;
// Notification by id
- (void) notification:(CDVInvokedUrlCommand*)command;
// Scheduled notification by id
- (void) scheduledNotification:(CDVInvokedUrlCommand*)command;
// Triggered notification by id
- (void) triggeredNotification:(CDVInvokedUrlCommand*)command;
// List of notifications by id
- (void) notifications:(CDVInvokedUrlCommand*)command;
// List of scheduled notifications by id
- (void) scheduledNotifications:(CDVInvokedUrlCommand*)command;
// List of triggered notifications by id
- (void) triggeredNotifications:(CDVInvokedUrlCommand*)command;
@end
/*
* Copyright (c) 2013 by appPlant GmbH. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -13,28 +17,23 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotification.h"
//#import "APPLocalNotificationOptions.h"
//#import "UNUserNotificationCenter+APPLocalNotification.h"
//#import "UNNotificationRequest+APPLocalNotification.h"
//#import "UNMutableNotificationContent+APPLocalNotification.h"
#import "APPNotificationOptions.h"
#import "UNUserNotificationCenter+APPLocalNotification.h"
#import "UNNotificationRequest+APPLocalNotification.h"
#import "APPNotificationContent.h"
@interface APPLocalNotification ()
// Property reader for [self app]
@property (readonly, getter=app) UIApplication* app;
// Property reader for [self center]
@property (readonly, getter=center) UNUserNotificationCenter* center;
// All events will be queued until deviceready has been fired
@property (strong, nonatomic) UIApplication* app;
@property (strong, nonatomic) UNUserNotificationCenter* center;
@property (readwrite, assign) BOOL deviceready;
// Event queue
@property (readonly, nonatomic, retain) NSMutableArray* eventQueue;
// IOS9: TODO remove later
@property (nonatomic, retain) CDVInvokedUrlCommand* command;
@end
@implementation APPLocalNotification
......@@ -46,6 +45,8 @@
/**
* Execute all queued events.
*
* @return [ Void ]
*/
- (void) deviceready:(CDVInvokedUrlCommand*)command
{
......@@ -57,48 +58,32 @@
[eventQueue removeAllObjects];
}
//
///**
// * Schedule a set of notifications.
// *
// * @param properties
// * A dict of properties for each notification
// */
//- (void) schedule:(CDVInvokedUrlCommand*)command
//{
// NSArray* notifications = command.arguments;
//
// [self.commandDelegate runInBackground:^{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// for (NSDictionary* options in notifications) {
// UNMutableNotificationContent* notification;
//
// notification = [[UNMutableNotificationContent alloc]
// initWithOptions:options];
//
// [self scheduleNotification:notification];
// //[self fireEvent:@"add" notification:notification];
// }
// } else {
// for (NSDictionary* options in notifications) {
// UILocalNotification* notification;
//
// notification = [[UILocalNotification alloc]
// initWithOptions:options];
//
// [self scheduleLocalNotification:[notification copy]];
// [self fireEvent:@"schedule" localnotification:notification];
//
// if (notifications.count > 1) {
// [NSThread sleepForTimeInterval:0.01];
// }
// }
// }
//
// [self execCallback:command];
// }];
//}
//
/**
* Schedule notifications.
*
* @param [Array<Hash>] properties A list of key-value properties.
*
* @return [ Void ]
*/
- (void) schedule:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
for (NSDictionary* options in notifications) {
APPNotificationContent* notification;
notification = [[APPNotificationContent alloc]
initWithOptions:options];
[self scheduleNotification:notification];
}
[self execCallback:command];
}];
}
///**
// * Update a set of notifications.
// *
......@@ -153,383 +138,342 @@
// [self execCallback:command];
// }];
//}
//
///**
// * Cancel a set of notifications.
// *
// * @param ids
// * The IDs of the notifications
// */
//- (void) cancel:(CDVInvokedUrlCommand*)command
//{
// [self.commandDelegate runInBackground:^{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// for (NSNumber* id in command.arguments) {
// UNNotificationRequest* notification;
//
// notification = [self.center getNotificationWithId:id];
//
// if (!notification)
// continue;
//
// [self.center cancelNotification:notification];
// [self fireEvent:@"cancel" notification:notification];
// }
// } else {
// for (NSNumber* id in command.arguments) {
// UILocalNotification* notification;
//
// notification = [self.app localNotificationWithId:id];
//
// if (!notification)
// continue;
//
// [self.app cancelLocalNotification:notification];
// [self fireEvent:@"cancel" localnotification:notification];
// }
// }
//
// [self execCallback:command];
// }];
//}
//
///**
// * Cancel all local notifications.
// */
//- (void) cancelAll:(CDVInvokedUrlCommand*)command
//{
// [self.commandDelegate runInBackground:^{
// [self cancelAllNotifications];
// [self fireEvent:@"cancelall"];
// [self execCallback:command];
// }];
//}
//
///**
// * Clear a set of notifications.
// *
// * @param ids
// * The IDs of the notifications
// */
//- (void) clear:(CDVInvokedUrlCommand*)command
//{
// [self.commandDelegate runInBackground:^{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// for (NSNumber* id in command.arguments) {
// UNNotificationRequest* notification;
//
// notification = [self.center getNotificationWithId:id];
//
// if (!notification)
// continue;
//
// [self.center clearNotification:notification];
// [self fireEvent:@"clear" notification:notification];
// }
// } else {
// for (NSNumber* id in command.arguments) {
// UILocalNotification* notification;
//
// notification = [self.app localNotificationWithId:id];
//
// if (!notification)
// continue;
//
// [self.app clearLocalNotification:notification];
// [self fireEvent:@"clear" localnotification:notification];
// }
// }
//
// [self execCallback:command];
// }];
//}
//
///**
// * Clear all local notifications.
// */
//- (void) clearAll:(CDVInvokedUrlCommand*)command
//{
// [self.commandDelegate runInBackground:^{
// [self clearAllNotifications];
// [self fireEvent:@"clearall"];
// [self execCallback:command];
// }];
//}
//
///**
// * If a notification by ID is present.
// *
// * @param id
// * The ID of the notification
// */
//- (void) isPresent:(CDVInvokedUrlCommand *)command
//{
// [self isPresent:command type:NotifcationTypeAll];
//}
//
///**
// * If a notification by ID is scheduled.
// *
// * @param id
// * The ID of the notification
// */
//- (void) isScheduled:(CDVInvokedUrlCommand*)command
//{
// [self isPresent:command type:NotifcationTypeScheduled];
//}
//
///**
// * Check if a notification with an ID is triggered.
// *
// * @param id
// * The ID of the notification
// */
//- (void) isTriggered:(CDVInvokedUrlCommand*)command
//{
// [self isPresent:command type:NotifcationTypeTriggered];
//}
//
///**
// * Check if a notification with an ID exists.
// *
// * @param type
// * The notification life cycle type
// */
//- (void) isPresent:(CDVInvokedUrlCommand*)command
// type:(APPNotificationType)type;
//{
// [self.commandDelegate runInBackground:^{
// NSNumber* id = [command argumentAtIndex:0];
// BOOL exist;
//
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// exist = [self.center notificationExist:id type:type];
// } else {
// if (type == NotifcationTypeAll) {
// exist = [self.app localNotificationExist:id];
// } else {
// exist = [self.app localNotificationExist:id type:type];
// }
// }
//
// CDVPluginResult* result;
// result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
// messageAsBool:exist];
//
// [self.commandDelegate sendPluginResult:result
// callbackId:command.callbackId];
// }];
//}
//
///**
// * List all ids from all local notifications.
// */
//- (void) getAllIds:(CDVInvokedUrlCommand*)command
//{
// [self getIds:command byType:NotifcationTypeAll];
//}
//
///**
// * List all ids from all pending notifications.
// */
//- (void) getScheduledIds:(CDVInvokedUrlCommand*)command
//{
// [self getIds:command byType:NotifcationTypeScheduled];
//}
//
///**
// * List all ids from all triggered notifications.
// */
//- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command
//{
// [self getIds:command byType:NotifcationTypeTriggered];
//}
//
///**
// * List of ids for given local notifications.
// *
// * @param type
// * Notification life cycle type
// * @param ids
// * The IDs of the notifications
// */
//- (void) getIds:(CDVInvokedUrlCommand*)command
// byType:(APPNotificationType)type;
//{
// [self.commandDelegate runInBackground:^{
// NSArray* ids;
//
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// ids = [self.center getNotificationIdsByType:type];
// } else {
// if (type == NotifcationTypeAll) {
// ids = [self.app localNotificationIds];
// } else {
// ids = [self.app localNotificationIdsByType:type];
// }
// }
//
// CDVPluginResult* result;
// result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
// messageAsArray:ids];
//
// [self.commandDelegate sendPluginResult:result
// callbackId:command.callbackId];
// }];
//}
//
///**
// * Propertys for given local notification.
// */
//- (void) getSingle:(CDVInvokedUrlCommand*)command
//{
// [self getOption:command byType:NotifcationTypeAll];
//}
//
///**
// * Propertya for given scheduled notification.
// */
//- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command
//{
// [self getOption:command byType:NotifcationTypeScheduled];
//}
//
//// Propertys for given triggered notification
//- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command
//{
// [self getOption:command byType:NotifcationTypeTriggered];
//}
//
///**
// * Property list for given local notifications.
// *
// * @param ids
// * The IDs of the notifications
// */
//- (void) getAll:(CDVInvokedUrlCommand*)command
//{
// [self getOptions:command byType:NotifcationTypeAll];
//}
//
///**
// * Property list for given scheduled notifications.
// *
// * @param ids
// * The IDs of the notifications
// */
//- (void) getScheduled:(CDVInvokedUrlCommand*)command
//{
// [self getOptions:command byType:NotifcationTypeScheduled];
//}
//
///**
// * Property list for given triggered notifications.
// *
// * @param ids
// * The IDs of the notifications
// */
//- (void) getTriggered:(CDVInvokedUrlCommand *)command
//{
// [self getOptions:command byType:NotifcationTypeTriggered];
//}
//
///**
// * Propertys for given triggered notification.
// *
// * @param type
// * Notification life cycle type
// * @param ids
// * The ID of the notification
// */
//- (void) getOption:(CDVInvokedUrlCommand*)command
// byType:(APPNotificationType)type;
//{
// [self.commandDelegate runInBackground:^{
// NSArray* ids = command.arguments;
// NSArray* notifications;
//
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// notifications = [self.center getNotificationOptionsByType:type
// andId:ids];
// } else {
// if (type == NotifcationTypeAll) {
// notifications = [self.app localNotificationOptionsById:ids];
// }
// else {
// notifications = [self.app localNotificationOptionsByType:type
// andId:ids];
// }
// }
//
// CDVPluginResult* result;
// result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
// messageAsDictionary:[notifications firstObject]];
//
// [self.commandDelegate sendPluginResult:result
// callbackId:command.callbackId];
// }];
//}
//
///**
// * Property list for given triggered notifications.
// *
// * @param type
// * Notification life cycle type
// * @param ids
// * The IDs of the notifications
// */
//- (void) getOptions:(CDVInvokedUrlCommand*)command
// byType:(APPNotificationType)type;
//{
// [self.commandDelegate runInBackground:^{
// NSArray* ids = command.arguments;
// NSArray* notifications;
//
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// if (type == NotifcationTypeAll && ids.count == 0) {
// notifications = [self.center getNotificationOptions];
// }
// else if (type == NotifcationTypeAll) {
// notifications = [self.center getNotificationOptionsById:ids];
// }
// else if (ids.count == 0) {
// notifications = [self.center getNotificationOptionsByType:type];
// }
// else {
// notifications = [self.center getNotificationOptionsByType:type
// andId:ids];
// }
// } else {
// if (type == NotifcationTypeAll && ids.count == 0) {
// notifications = [self.app localNotificationOptions];
// }
// else if (type == NotifcationTypeAll) {
// notifications = [self.app localNotificationOptionsById:ids];
// }
// else if (ids.count == 0) {
// notifications = [self.app localNotificationOptionsByType:type];
// }
// else {
// notifications = [self.app localNotificationOptionsByType:type
// andId:ids];
// }
// }
//
// CDVPluginResult* result;
// result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
// messageAsArray:notifications];
//
// [self.commandDelegate sendPluginResult:result
// callbackId:command.callbackId];
// }];
//}
/**
* Clear notifications by id.
*
* @param [ Array<Int> ] The IDs of the notifications to clear.
*
* @return [ Void ]
*/
- (void) clear:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
for (NSNumber* id in command.arguments) {
UNNotificationRequest* notification;
notification = [self.center getNotificationWithId:id];
if (!notification)
continue;
[self.center clearNotification:notification];
[self fireEvent:@"clear" notification:notification];
}
[self execCallback:command];
}];
}
/**
* Clear all local notifications.
*
* @return [ Void ]
*/
- (void) clearAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self.center clearAllNotifications];
[self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"clearall"];
[self execCallback:command];
}];
}
/**
* Cancel notifications by id.
*
* @param [ Array<Int> ] The IDs of the notifications to clear.
*
* @return [ Void ]
*/
- (void) cancel:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
for (NSNumber* id in command.arguments) {
UNNotificationRequest* notification;
notification = [self.center getNotificationWithId:id];
if (!notification)
continue;
[self.center cancelNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
[self execCallback:command];
}];
}
/**
* Cancel all local notifications.
*
* @return [ Void ]
*/
- (void) cancelAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self.center cancelAllNotifications];
[self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"cancelall"];
[self execCallback:command];
}];
}
/**
* If a notification by ID is present.
*
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isPresent:(CDVInvokedUrlCommand *)command
{
[self exist:command byType:NotifcationTypeAll];
}
/**
* If a notification by ID is scheduled.
*
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isScheduled:(CDVInvokedUrlCommand*)command
{
[self exist:command byType:NotifcationTypeScheduled];
}
/**
* Check if a notification with an ID is triggered.
*
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isTriggered:(CDVInvokedUrlCommand*)command
{
[self exist:command byType:NotifcationTypeTriggered];
}
/**
* Check if a notification exists by ID and type.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) exist:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSNumber* id = [command argumentAtIndex:0];
BOOL exist = [_center notificationExist:id type:type];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:exist];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* List of all notification IDs.
*
* @return [ Void ]
*/
- (void) ids:(CDVInvokedUrlCommand*)command
{
[self ids:command byType:NotifcationTypeAll];
}
/**
* List of all scheduled notification IDs.
*
* @return [ Void ]
*/
- (void) scheduledIds:(CDVInvokedUrlCommand*)command
{
[self ids:command byType:NotifcationTypeScheduled];
}
/**
* List of all triggered notification IDs.
*
* @return [ Void ]
*/
- (void) triggeredIds:(CDVInvokedUrlCommand*)command
{
[self ids:command byType:NotifcationTypeTriggered];
}
/**
* List of ids for given local notifications.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) ids:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = [self.center getNotificationIdsByType:type];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:ids];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) notification:(CDVInvokedUrlCommand*)command
{
[self notification:command byType:NotifcationTypeAll];
}
/**
* Scheduled notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) scheduledNotification:(CDVInvokedUrlCommand*)command
{
[self notification:command byType:NotifcationTypeScheduled];
}
/**
* Triggered notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) triggeredNotification:(CDVInvokedUrlCommand*)command
{
[self notification:command byType:NotifcationTypeTriggered];
}
/**
* Notification by type and id.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) notification:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
notifications = [_center getNotificationOptionsByType:type andId:ids];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:[notifications firstObject]];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* List of notifications by id.
*
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @return [ Void ]
*/
- (void) notifications:(CDVInvokedUrlCommand*)command
{
[self notifications:command byType:NotifcationTypeAll];
}
/**
* List of scheduled notifications by id.
*
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @return [ Void ]
*/
- (void) scheduledNotifications:(CDVInvokedUrlCommand*)command
{
[self notifications:command byType:NotifcationTypeScheduled];
}
/**
* List of triggered notifications by id.
*
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @return [ Void ]
*/
- (void) triggeredNotifications:(CDVInvokedUrlCommand *)command
{
[self notifications:command byType:NotifcationTypeTriggered];
}
/**
* List of notifications by type and id.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) notifications:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
if (type == NotifcationTypeAll && ids.count == 0) {
notifications = [_center getNotificationOptions];
}
else if (type == NotifcationTypeAll) {
notifications = [_center getNotificationOptionsById:ids];
}
else if (ids.count == 0) {
notifications = [_center getNotificationOptionsByType:type];
}
else {
notifications = [_center getNotificationOptionsByType:type
andId:ids];
}
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:notifications];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Check for permission to show notifications.
*
* @return [ Void ]
*/
- (void) check:(CDVInvokedUrlCommand*)command
{
[self.center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
[_center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized;
BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled;
BOOL permitted = authorized && enabled;
......@@ -545,6 +489,8 @@
/**
* Request for permission to show notifcations.
*
* @return [ Void ]
*/
- (void) request:(CDVInvokedUrlCommand*)command
{
......@@ -557,25 +503,28 @@
}
#pragma mark -
#pragma mark Core Logic
#pragma mark Private
/**
* Schedule the local notification.
*/
- (void) scheduleNotification:(APPNotificationContent*)notification
{
__weak APPLocalNotification* weakSelf = self;
UNNotificationRequest* request = notification.request;
[_center addNotificationRequest:request withCompletionHandler:^(NSError* e) {
__strong APPLocalNotification* strongSelf = weakSelf;
[strongSelf fireEvent:@"add" notification:request];
}];
}
///**
// * Schedule the local notification.
// */
//- (void) scheduleNotification:(UNMutableNotificationContent*)notification
//{
// [self.center addNotificationRequest:notification.request
// withCompletionHandler:^(NSError* e) {
// [self fireEvent:@"add" notification:notification.request];
// }];
//}
//
///**
// * Update the local notification.
// */
//- (void) updateNotification:(UILocalNotification*)notification
// withOptions:(NSDictionary*)newOptions
//{
//{APPNotificationRequest*
// NSMutableDictionary* options = [notification.userInfo mutableCopy];
//
// [options addEntriesFromDictionary:newOptions];
......@@ -586,72 +535,44 @@
////
//// [self scheduleLocalNotification:notification];
//}
//
///**
// * Cancel all local notifications.
// */
//- (void) cancelAllNotifications
//{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// [self.center cancelAllNotifications];
// } else {
// [self.app cancelAllLocalNotifications];
// }
//
// [self.app setApplicationIconBadgeNumber:0];
//}
//
///**
// * Clear all local notifications.
// */
//- (void) clearAllNotifications
//{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// [self.center clearAllNotifications];
// } else {
// [self.app clearAllLocalNotifications];
// }
//
// [self.app setApplicationIconBadgeNumber:0];
//}
//
//#pragma mark -
//#pragma mark Delegates
//
///**
// * Called when a notification is delivered to a foreground app.
// */
//- (void) userNotificationCenter:(UNUserNotificationCenter *)center
// willPresentNotification:(UNNotification *)notification
// withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
//{
// [self fireEvent:@"trigger" notification:notification.request];
// completionHandler(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
//}
//
//
///**
// * Called to let your app know which action was selected by the user for a given
// * notification.
// */
//- (void) userNotificationCenter:(UNUserNotificationCenter *)center
// didReceiveNotificationResponse:(UNNotificationResponse *)response
// withCompletionHandler:(void (^)())completionHandler
//{
// UNNotificationRequest* notification = response.notification.request;
//
// [self fireEvent:@"click" notification:notification];
//
// if ([notification.options isRepeating]) {
// [self.center clearNotification:notification];
// [self fireEvent:@"clear" notification:notification];
// } else {
// [self.center cancelNotification:notification];
// [self fireEvent:@"cancel" notification:notification];
// }
//
// completionHandler();
//}
#pragma mark -
#pragma mark UNUserNotificationCenterDelegate
/**
* Called when a notification is delivered to the app while being in foreground.
*/
- (void) userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
[self fireEvent:@"trigger" notification:notification.request];
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
/**
* Called to let your app know which action was selected by the user for a given
* notification.
*/
- (void) userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler
{
UNNotificationRequest* notification = response.notification.request;
NSString* action = response.actionIdentifier;
NSString* event = action;
if ([action isEqualToString:UNNotificationDefaultActionIdentifier]) {
event = @"click";
} else
if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
event = @"clear";
}
[self fireEvent:event notification:notification];
completionHandler();
}
#pragma mark -
#pragma mark Life Cycle
......@@ -662,249 +583,83 @@
- (void) pluginInitialize
{
eventQueue = [[NSMutableArray alloc] init];
_app = [UIApplication sharedApplication];
_center = [UNUserNotificationCenter currentNotificationCenter];
self.center.delegate = self;
_center.delegate = self;
[_center registerGeneralNotificationCategory];
}
#pragma mark -
#pragma mark Helper
///**
// * Retrieves the application state
// *
// * @return
// * Either "background" or "foreground"
// */
//- (NSString*) applicationState
//{
// UIApplicationState state = [self.app applicationState];
//
// bool isActive = state == UIApplicationStateActive;
//
// return isActive ? @"foreground" : @"background";
//}
//
///**
// * Simply invokes the callback without any parameter.
// */
//- (void) execCallback:(CDVInvokedUrlCommand*)command
//{
// CDVPluginResult *result = [CDVPluginResult
// resultWithStatus:CDVCommandStatus_OK];
//
// [self.commandDelegate sendPluginResult:result
// callbackId:command.callbackId];
//}
//
///**
// * Short hand for shared application instance.
// */
//- (UIApplication*) app
//{
// return [UIApplication sharedApplication];
//}
/**
* Retrieve the state of the application.
*
* @return "background" or "foreground"
*/
- (NSString*) applicationState
{
UIApplicationState state = [_app applicationState];
bool isActive = state == UIApplicationStateActive;
return isActive ? @"foreground" : @"background";
}
/**
* Short hand for current notification center.
* Simply invokes the callback without any parameter.
*/
- (UNUserNotificationCenter*) center
- (void) execCallback:(CDVInvokedUrlCommand*)command
{
return [UNUserNotificationCenter currentNotificationCenter];
CDVPluginResult *result = [CDVPluginResult
resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}
///**
// * Fire general event.
// */
//- (void) fireEvent:(NSString*)event
//{
// [self fireEvent:event notification:NULL];
//}
//
///**
// * Fire event for local notification.
// */
//- (void) fireEvent:(NSString*)event
// notification:(UNNotificationRequest*)notification
//{
// NSString* js;
// NSString* appState = [self applicationState];
// NSString* params = [NSString stringWithFormat:@"\"%@\"", appState];
//
// if (notification) {
// NSString* args = [notification encodeToJSON];
// params = [NSString stringWithFormat:@"%@,'%@'", args, appState];
// }
//
// js = [NSString stringWithFormat:
// @"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
// event, params];
//
// if (deviceready) {
// [self.commandDelegate evalJs:js];
// } else {
// [self.eventQueue addObject:js];
// }
//}
//
//#pragma mark -
//#pragma mark ios 9
//
///**
// * Schedule the local notification.
// */
//- (void) scheduleLocalNotification:(UILocalNotification*)notification
//{
// [self cancelForerunnerLocalNotification:notification];
// [self.app scheduleLocalNotification:notification];
//}
//
///**
// * Update the local notification.
// */
//- (void) updateLocalNotification:(UILocalNotification*)notification
// withOptions:(NSDictionary*)newOptions
//{
// NSMutableDictionary* options = [notification.userInfo mutableCopy];
//
// [options addEntriesFromDictionary:newOptions];
// [options setObject:[NSDate date] forKey:@"updatedAt"];
//
// notification = [[UILocalNotification alloc]
// initWithOptions:options];
//
// [self scheduleLocalNotification:notification];
//}
//
///**
// * Cancel a maybe given forerunner with the same ID.
// */
//- (void) cancelForerunnerLocalNotification:(UILocalNotification*)notification
//{
// NSNumber* id = notification.options.id;
// UILocalNotification* forerunner;
//
// forerunner = [self.app localNotificationWithId:id];
//
// if (!forerunner)
// return;
//
// [self.app cancelLocalNotification:forerunner];
//}
//
///**
// * Cancels all non-repeating local notification older then
// * a specific amount of seconds
// */
//- (void) cancelAllNotificationsWhichAreOlderThen:(float)seconds
//{
// NSArray* notifications;
//
// notifications = [self.app localNotifications];
//
// for (UILocalNotification* notification in notifications)
// {
// if (![notification isRepeating]
// && notification.timeIntervalSinceFireDate > seconds)
// {
// [self.app cancelLocalNotification:notification];
// [self fireEvent:@"cancel" localnotification:notification];
// }
// }
//}
//
///**
// * Calls the cancel or trigger event after a local notification was received.
// * Cancels the local notification if autoCancel was set to true.
// */
//- (void) didReceiveLocalNotification:(NSNotification*)localNotification
//{
// UILocalNotification* notification = [localNotification object];
//
// if ([notification userInfo] == NULL || [notification wasUpdated])
// return;
//
// NSTimeInterval timeInterval = [notification timeIntervalSinceLastTrigger];
// NSString* event = timeInterval < 0.2 && deviceready ? @"trigger" : @"click";
//
// [self fireEvent:event localnotification:notification];
//
// if (![event isEqualToString:@"click"])
// return;
//
// if ([notification isRepeating]) {
// [self fireEvent:@"clear" localnotification:notification];
// } else {
// [self.app cancelLocalNotification:notification];
// [self fireEvent:@"cancel" localnotification:notification];
// }
//}
//
///**
// * Called when app has started
// * (by clicking on a local notification).
// */
//- (void) didFinishLaunchingWithOptions:(NSNotification*)notification
//{
// NSDictionary* launchOptions = [notification userInfo];
//
// UILocalNotification* localNotification;
//
// localNotification = [launchOptions objectForKey:
// UIApplicationLaunchOptionsLocalNotificationKey];
//
// if (localNotification) {
// [self didReceiveLocalNotification:
// [NSNotification notificationWithName:CDVLocalNotification
// object:localNotification]];
// }
//}
//
///**
// * Called on notification settings registration is completed.
// */
//- (void) didRegisterUserNotificationSettings:(UIUserNotificationSettings*)settings
//{
// if (_command) {
// [self hasPermission:_command];
// _command = NULL;
// }
//}
//
///**
// * Cancels all single non-repeating notifications which are older then 5 days
// * before the app terminates.
// */
//- (void) onAppTerminate
//{
// [self cancelAllNotificationsWhichAreOlderThen:432000];
//}
//
///**
// * Fire event for local notification.
// */
//- (void) fireEvent:(NSString*)event localnotification:(UILocalNotification*)notification
//{
// NSString* js;
// NSString* params = [NSString stringWithFormat:
// @"\"%@\"", self.applicationState];
//
// if (notification) {
// NSString* args = [notification encodeToJSON];
//
// params = [NSString stringWithFormat:
// @"%@,'%@'",
// args, self.applicationState];
// }
//
// js = [NSString stringWithFormat:
// @"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
// event, params];
//
// if (deviceready) {
// [self.commandDelegate evalJs:js];
// } else {
// [self.eventQueue addObject:js];
// }
//}
/**
* Fire general event.
*
* @param [ NSString* ] event The name of the event to fire.
*
* @return [ Void ]
*/
- (void) fireEvent:(NSString*)event
{
[self fireEvent:event notification:NULL];
}
/**
* Fire event for about a local notification.
*
* @param [ NSString* ] event The name of the event to fire.
* @param [ APPNotificationRequest* ] notification The local notification.
*
* @return [ Void ]
*/
- (void) fireEvent:(NSString*)event
notification:(UNNotificationRequest*)request
{
NSString* js;
NSString* appState = [self applicationState];
NSString* params = [NSString stringWithFormat:@"\"%@\"", appState];
if (request) {
NSString* args = [request encodeToJSON];
params = [NSString stringWithFormat:@"%@,'%@'", args, appState];
}
js = [NSString stringWithFormat:
@"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
event, params];
if (deviceready) {
[self.commandDelegate evalJs:js];
} else {
[self.eventQueue addObject:js];
}
}
@end
......@@ -21,27 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import <UserNotifications/UNNotificationSound.h>
#import <UserNotifications/UNNotificationRequest.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "APPNotificationOptions.h"
@interface APPLocalNotificationOptions : NSObject
@import UserNotifications;
- (id) initWithDict:(NSDictionary*)dict;
@interface APPNotificationContent : UNMutableNotificationContent
@property (readonly, getter=id) NSNumber* id;
@property (readonly, getter=identifier) NSString* identifier;
@property (readonly, getter=title) NSString* title;
@property (readonly, getter=subtitle) NSString* subtitle;
@property (readonly, getter=badge) NSNumber* badge;
@property (readonly, getter=text) NSString* text;
@property (readonly, getter=sound) UNNotificationSound* sound;
@property (readonly, getter=userInfo) NSDictionary* userInfo;
// If it's a repeating notification
- (BOOL) isRepeating;
// how and when to trigger the notification
- (UNNotificationTrigger*) trigger;
- (id) initWithOptions:(NSDictionary*)dict;
- (APPNotificationOptions*) options;
- (UNNotificationRequest*) request;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationContent.h"
#import "APPNotificationOptions.h"
#import "UNUserNotificationCenter+APPLocalNotification.h"
#import <objc/runtime.h>
@import UserNotifications;
static char optionsKey;
@implementation APPNotificationContent : UNMutableNotificationContent
#pragma mark -
#pragma mark Init
/**
* Initialize a notification with the given options.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ UNMutableNotificationContent ]
*/
- (id) initWithOptions:(NSDictionary*)dict
{
self = [self init];
[self setUserInfo:dict];
[self __init];
return self;
}
/**
* Initialize a notification by using the options found under userInfo.
*
* @return [ Void ]
*/
- (void) __init
{
APPNotificationOptions* options = self.options;
self.title = options.title;
self.subtitle = options.subtitle;
self.body = options.text;
self.sound = options.sound;
self.badge = options.badge;
self.attachments = options.attachments;
self.categoryIdentifier = kAPPGeneralCategory;
}
#pragma mark -
#pragma mark Public
/**
* The options used to initialize the notification.
*
* @return [ APPNotificationOptions* ] options
*/
- (APPNotificationOptions*) options
{
APPNotificationOptions* options = [self getOptions];
if (!options) {
options = [[APPNotificationOptions alloc]
initWithDict:[self userInfo]];
[self setOptions:options];
}
return options;
}
/**
* The notifcations request ready to add to the notification center including
* all informations about trigger behavior.
*
* @return [ UNNotificationRequest* ]
*/
- (UNNotificationRequest*) request
{
APPNotificationOptions* opts = [self getOptions];
return [UNNotificationRequest requestWithIdentifier:opts.identifier
content:self
trigger:opts.trigger];
}
#pragma mark -
#pragma mark Private
/**
* The options used to initialize the notification.
*
* @return [ APPNotificationOptions* ]
*/
- (APPNotificationOptions*) getOptions
{
return objc_getAssociatedObject(self, &optionsKey);
}
/**
* Set the options used to initialize the notification.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ Void ]
*/
- (void) setOptions:(APPNotificationOptions*)options
{
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
......@@ -21,43 +21,21 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UILocalNotification+APPLocalNotification.ios9.h"
@interface UIApplication (APPLocalNotification)
@property (readonly, getter=localNotifications) NSArray* localNotifications;
@property (readonly, getter=localNotificationIds) NSArray* localNotificationIds;
// If the app has the permission to schedule local notifications
- (BOOL) hasPermissionToScheduleLocalNotifications;
// Ask for permission to schedule local notifications
- (void) registerPermissionToScheduleLocalNotifications;
// List of all local notification IDs from given type
- (NSArray*) localNotificationIdsByType:(APPNotificationType)type;
// If local notification with ID exists
- (BOOL) localNotificationExist:(NSNumber*)id;
// If local notification with ID and type exists
- (BOOL) localNotificationExist:(NSNumber*)id type:(APPNotificationType)type;
// Local notification by ID
- (UILocalNotification*) localNotificationWithId:(NSNumber*)id;
// Local notification by ID and type
- (UILocalNotification*) localNotificationWithId:(NSNumber*)id andType:(APPNotificationType)type;
// Property list from all local notifications
- (NSArray*) localNotificationOptions;
// Property list from given local notifications
- (NSArray*) localNotificationOptionsById:(NSArray*)ids;
// Property list from all local notifications with type constraint
- (NSArray*) localNotificationOptionsByType:(APPNotificationType)type;
// Property list from given local notifications with type constraint
- (NSArray*) localNotificationOptionsByType:(APPNotificationType)type andId:(NSArray*)ids;
// Clear single local notfications
- (void) clearLocalNotification:(UILocalNotification*)notification;
// Clear all local notfications
- (void) clearAllLocalNotifications;
@import UserNotifications;
@interface APPNotificationOptions : NSObject
@property (readonly, getter=id) NSNumber* id;
@property (readonly, getter=identifier) NSString* identifier;
@property (readonly, getter=title) NSString* title;
@property (readonly, getter=subtitle) NSString* subtitle;
@property (readonly, getter=badge) NSNumber* badge;
@property (readonly, getter=text) NSString* text;
@property (readonly, getter=sound) UNNotificationSound* sound;
@property (readonly, getter=attachments) NSArray<UNNotificationAttachment *> * attachments;
@property (readonly, getter=userInfo) NSDictionary* userInfo;
- (id) initWithDict:(NSDictionary*)dict;
- (UNNotificationTrigger*) trigger;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationOptions.h"
@import UserNotifications;
@interface APPNotificationOptions ()
// The dictionary which contains all notification properties
@property(nonatomic, retain) NSDictionary* dict;
@end
@implementation APPNotificationOptions : NSObject
@synthesize dict;
#pragma mark -
#pragma mark Initialization
/**
* Initialize by using the given property values.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ APPNotificationOptions ]
*/
- (id) initWithDict:(NSDictionary*)dictionary
{
self = [self init];
self.dict = dictionary;
return self;
}
#pragma mark -
#pragma mark Properties
/**
* The ID for the notification.
*
* @return [ NSNumber* ]
*/
- (NSNumber*) id
{
NSInteger id = [[dict objectForKey:@"id"] integerValue];
return [NSNumber numberWithInteger:id];
}
/**
* The ID for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) identifier
{
return [NSString stringWithFormat:@"%@", self.id];
}
/**
* The title for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) title
{
return [dict objectForKey:@"title"];
}
/**
* The subtitle for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) subtitle
{
NSArray *parts = [self.title componentsSeparatedByString:@"\n"];
return parts.count < 2 ? @"" : [parts objectAtIndex:1];
}
/**
* The text for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) text
{
return [dict objectForKey:@"text"];
}
/**
* The badge number for the notification.
*
* @return [ NSNumber* ]
*/
- (NSNumber*) badge
{
return [NSNumber numberWithInt:[[dict objectForKey:@"badge"] intValue]];
}
/**
* The sound file for the notification.
*
* @return [ UNNotificationSound* ]
*/
- (UNNotificationSound*) sound
{
NSString* path = [dict objectForKey:@"sound"];
NSString* file;
if (!path.length)
return NULL;
if ([path isEqualToString:@"res://platform_default"])
return [UNNotificationSound defaultSound];
if ([path hasPrefix:@"file:/"]) {
file = [self soundNameForAsset:path];
} else
if ([path hasPrefix:@"res:"]) {
file = [self soundNameForResource:path];
}
return [UNNotificationSound soundNamed:file];
}
/**
* The date when to fire the notification.
*
* @return [ NSDate* ]
*/
- (NSDate*) fireDate
{
double timestamp = [[dict objectForKey:@"at"]
doubleValue];
return [NSDate dateWithTimeIntervalSince1970:timestamp];
}
- (NSArray<UNNotificationAttachment *> *) attachments
{
NSArray* paths = [dict objectForKey:@"attachments"];
NSMutableArray* attachments = [[NSMutableArray alloc] init];
if (!paths)
return attachments;
for (NSString* path in paths) {
NSURL* url = [self urlForAttachmentPath:path];
UNNotificationAttachment* attachment;
attachment = [UNNotificationAttachment attachmentWithIdentifier:path
URL:url
options:NULL
error:NULL];
if (attachment) {
[attachments addObject:attachment];
}
}
return attachments;
}
#pragma mark -
#pragma mark Public
/**
* Specify how and when to trigger the notification.
*
* @return [ UNNotificationTrigger* ]
*/
- (UNNotificationTrigger*) trigger
{
if ([self isRepeating])
return [self repeatingTrigger];
return [self nonRepeatingTrigger];
}
/**
* The notification's user info dict.
*
* @return [ NSDictionary* ]
*/
- (NSDictionary*) userInfo
{
if ([dict objectForKey:@"updatedAt"]) {
NSMutableDictionary* data = [dict mutableCopy];
[data removeObjectForKey:@"updatedAt"];
return data;
}
return dict;
}
#pragma mark -
#pragma mark Private
/**
* If the notification shall be repeating.
*
* @return [ BOOL ]
*/
- (BOOL) isRepeating
{
id every = [dict objectForKey:@"every"];
if ([every isKindOfClass:NSString.class])
return ((NSString*) every).length > 0;
if ([every isKindOfClass:NSDictionary.class])
return ((NSDictionary*) every).count > 0;
return every > 0;
}
/**
* Non repeating trigger.
*
* @return [ UNTimeIntervalNotificationTrigger* ]
*/
- (UNTimeIntervalNotificationTrigger*) nonRepeatingTrigger
{
return [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:[self timeInterval] repeats:NO];
}
/**
* Repeating trigger.
*
* @return [ UNNotificationTrigger* ]
*/
- (UNNotificationTrigger*) repeatingTrigger
{
id every = [dict objectForKey:@"every"];
if ([every isKindOfClass:NSString.class])
return [self repeatingTriggerWithDateMatchingComponents];
if ([every isKindOfClass:NSDictionary.class])
return [self repeatingTriggerWithCustomDateMatchingComponents];
return [self repeatingTriggerWithTimeInterval];
}
/**
* A trigger based on a calendar time defined by the user.
*
* @return [ UNTimeIntervalNotificationTrigger* ]
*/
- (UNTimeIntervalNotificationTrigger*) repeatingTriggerWithTimeInterval
{
long interval = [[dict objectForKey:@"every"] longValue];
if (interval < 60) {
NSLog(@"time interval must be at least 60 if repeating");
interval = 60;
}
return [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:interval repeats:YES];
}
/**
* A repeating trigger based on a calendar time intervals defined by the plugin.
*
* @return [ UNCalendarNotificationTrigger* ]
*/
- (UNCalendarNotificationTrigger*) repeatingTriggerWithDateMatchingComponents
{
NSCalendar* cal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *date = [cal components:[self repeatInterval]
fromDate:[self fireDate]];
date.timeZone = [NSTimeZone defaultTimeZone];
return [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:YES];
}
/**
* A repeating trigger based on a calendar time intervals defined by the user.
*
* @return [ UNCalendarNotificationTrigger* ]
*/
- (UNCalendarNotificationTrigger*) repeatingTriggerWithCustomDateMatchingComponents
{
NSCalendar* cal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *date = [self customDateComponents];
date.calendar = cal;
date.timeZone = [NSTimeZone defaultTimeZone];
return [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:YES];
}
/**
* The time interval between the next fire date and now.
*
* @return [ double ]
*/
- (double) timeInterval
{
return MAX(0.01f, [self.fireDate timeIntervalSinceDate:[NSDate date]]);
}
/**
* The repeat interval for the notification.
*
* @return [ NSCalendarUnit ]
*/
- (NSCalendarUnit) repeatInterval
{
NSString* interval = [dict objectForKey:@"every"];
NSCalendarUnit units = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"minute"])
return NSCalendarUnitSecond;
if ([interval isEqualToString:@"hour"])
return NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"day"])
return NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"week"])
return NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"month"])
return NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"year"])
return NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
return units;
}
/**
* The repeat interval for the notification.
*
* @return [ NSDateComponents* ]
*/
- (NSDateComponents*) customDateComponents
{
NSDateComponents* date = [[NSDateComponents alloc] init];
NSDictionary* every = [dict objectForKey:@"every"];
for (NSString* key in every) {
long value = [[every valueForKey:key] longValue];
if ([key isEqualToString:@"second"]) {
date.second = value;
} else
if ([key isEqualToString:@"minute"]) {
date.minute = value;
} else
if ([key isEqualToString:@"hour"]) {
date.hour = value;
} else
if ([key isEqualToString:@"day"]) {
date.day = value;
} else
if ([key isEqualToString:@"weekday"]) {
date.weekday = value;
} else
if ([key isEqualToString:@"weekdayOrdinal"]) {
date.weekdayOrdinal = value;
} else
if ([key isEqualToString:@"week"]) {
date.weekOfYear = value;
} else
if ([key isEqualToString:@"weekOfMonth"]) {
date.weekOfMonth = value;
} else
if ([key isEqualToString:@"month"]) {
date.month = value;
} else
if ([key isEqualToString:@"quarter"]) {
date.quarter = value;
} else
if ([key isEqualToString:@"year"]) {
date.year = value;
}
}
return date;
}
/**
* Convert an assets path to an valid sound name attribute.
*
* @param [ NSString* ] path A relative assets file path.
*
* @return [ NSString* ]
*/
- (NSString*) soundNameForAsset:(NSString*)path
{
return [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"www"];
}
/**
* Convert a ressource path to an valid sound name attribute.
*
* @param [ NSString* ] path A relative ressource file path.
*
* @return [ NSString* ]
*/
- (NSString*) soundNameForResource:(NSString*)path
{
return [path pathComponents].lastObject;
}
/**
* URL for the specified attachment path.
*
* @param [ NSString* ] path Absolute/relative path or a base64 data.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAttachmentPath:(NSString*)path
{
if ([path hasPrefix:@"file:///"])
{
return [self urlForFile:path];
}
else if ([path hasPrefix:@"res:"])
{
return [self urlForResource:path];
}
else if ([path hasPrefix:@"file://"])
{
return [self urlForAsset:path];
}
else if ([path hasPrefix:@"app://"])
{
return [self urlForAppInternalPath:path];
}
else if ([path hasPrefix:@"base64:"])
{
return [self urlFromBase64:path];
}
NSFileManager* fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:path]){
NSLog(@"File not found: %@", path);
}
return [NSURL fileURLWithPath:path];
}
/**
* URL to an absolute file path.
*
* @param [ NSString* ] path An absolute file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForFile:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"file://"
withString:@""];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL to a resource file.
*
* @param [ NSString* ] path A relative file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForResource:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* bundlePath = [mainBundle bundlePath];
if ([path isEqualToString:@"res://icon"]) {
path = @"res://AppIcon60x60@3x.png";
}
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"res:/"
withString:@""];
absPath = [bundlePath stringByAppendingString:absPath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL to an asset file.
*
* @param path A relative www file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAsset:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* bundlePath = [mainBundle bundlePath];
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"/www"];
absPath = [bundlePath stringByAppendingString:absPath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL for an internal app path.
*
* @param [ NSString* ] path A relative file path from main bundle dir.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAppInternalPath:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* absPath = [mainBundle bundlePath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL for a base64 encoded string.
*
* @param [ NSString* ] base64String Base64 encoded string.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlFromBase64:(NSString*)base64String
{
NSString *filename = [self getBasenameFromAttachmentPath:base64String];
NSUInteger length = [base64String length];
NSRegularExpression *regex;
NSString *dataString;
regex = [NSRegularExpression regularExpressionWithPattern:@"^base64:[^/]+.."
options:NSRegularExpressionCaseInsensitive
error:Nil];
dataString = [regex stringByReplacingMatchesInString:base64String
options:0
range:NSMakeRange(0, length)
withTemplate:@""];
NSData* data = [[NSData alloc] initWithBase64EncodedString:dataString
options:0];
return [self urlForData:data withFileName:filename];
}
/**
* Extract the attachments basename.
*
* @param [ NSString* ] path The file path or base64 data.
*
* @return [ NSString* ]
*/
- (NSString*) getBasenameFromAttachmentPath:(NSString*)path
{
if ([path hasPrefix:@"base64:"]) {
NSString* pathWithoutPrefix;
pathWithoutPrefix = [path stringByReplacingOccurrencesOfString:@"base64:"
withString:@""];
return [pathWithoutPrefix substringToIndex:
[pathWithoutPrefix rangeOfString:@"//"].location];
}
return path;
}
/**
* Write the data into a temp file.
*
* @param [ NSData* ] data The data to save to file.
* @param [ NSString* ] name The name of the file.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForData:(NSData*)data withFileName:(NSString*) filename
{
NSFileManager* fm = [NSFileManager defaultManager];
NSString* tempDir = NSTemporaryDirectory();
[fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES
attributes:NULL
error:NULL];
NSString* absPath = [tempDir stringByAppendingPathComponent:filename];
NSURL* url = [NSURL fileURLWithPath:absPath];
[data writeToURL:url atomically:NO];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return url;
}
@end
......@@ -21,18 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotificationOptions.h"
#import "APPNotificationOptions.h"
@import UserNotifications;
@interface UNMutableNotificationContent (APPLocalNotification)
@interface UNNotificationRequest (APPLocalNotification)
// Initialize a new local notification
- (id) initWithOptions:(NSDictionary*)dict;
// The options provided by the plug-in
- (APPLocalNotificationOptions*) options;
// Fully configured request to add the notification to the notification center
- (UNNotificationRequest*) request;
- (APPNotificationOptions*) options;
// Encode the user info dict to JSON
- (NSString*) encodeToJSON;
......
......@@ -21,62 +21,44 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UNMutableNotificationContent+APPLocalNotification.h"
#import "APPLocalNotificationOptions.h"
#import "APPNotificationOptions.h"
#import "UNNotificationRequest+APPLocalNotification.h"
#import "APPNotificationContent.h"
#import <objc/runtime.h>
@import UserNotifications;
static char optionsKey;
@implementation UNMutableNotificationContent (APPLocalNotification)
#pragma mark -
#pragma mark Init
@implementation UNNotificationRequest (APPLocalNotification)
/**
* Initialize a local notification with the given options when calling on JS side:
* notification.local.add(options)
* Get associated option object
*/
- (id) initWithOptions:(NSDictionary*)dict
- (APPNotificationOptions*) getOptions
{
self = [self init];
[self setUserInfo:dict];
[self __init];
return self;
return objc_getAssociatedObject(self, &optionsKey);
}
/**
* Applies the given options when calling on JS side:
* notification.local.add(options)
* Set associated option object
*/
- (void) __init
- (void) setOptions:(APPNotificationOptions*)options
{
APPLocalNotificationOptions* options = self.options;
self.title = options.title;
self.subtitle = options.subtitle;
self.body = options.text;
self.sound = options.sound;
self.badge = options.badge;
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
#pragma mark Methods
/**
* The options provided by the plug-in.
*/
- (APPLocalNotificationOptions*) options
- (APPNotificationOptions*) options
{
APPLocalNotificationOptions* options = [self getOptions];
APPNotificationOptions* options = [self getOptions];
if (!options) {
options = [[APPLocalNotificationOptions alloc]
initWithDict:[self userInfo]];
options = [[APPNotificationOptions alloc]
initWithDict:[self.content userInfo]];
[self setOptions:options];
}
......@@ -85,43 +67,13 @@ static char optionsKey;
}
/**
* Get associated option object
*/
- (APPLocalNotificationOptions*) getOptions
{
return objc_getAssociatedObject(self, &optionsKey);
}
/**
* Set associated option object
*/
- (void) setOptions:(APPLocalNotificationOptions*)options
{
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
/**
* The notifcations request ready to add to the notification center including
* all informations about trigger behavior.
*/
- (UNNotificationRequest*) request
{
APPLocalNotificationOptions* opts = [self getOptions];
return [UNNotificationRequest requestWithIdentifier:opts.identifier
content:self
trigger:opts.trigger];
}
/**
* Encode the user info dict to JSON.
*/
- (NSString*) encodeToJSON
{
NSString* json;
NSData* data;
NSMutableDictionary* obj = [self.userInfo mutableCopy];
NSMutableDictionary* obj = [self.content.userInfo mutableCopy];
[obj removeObjectForKey:@"updatedAt"];
......
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationContent.h"
@interface UNUserNotificationCenter (APPLocalNotification)
extern NSString * const kAPPGeneralCategory;
typedef NS_ENUM(NSUInteger, APPNotificationType) {
NotifcationTypeAll = 0,
NotifcationTypeScheduled = 1,
NotifcationTypeTriggered = 2
};
#define APPNotificationType_DEFINED
@property (readonly, getter=getNotifications) NSArray* localNotifications;
@property (readonly, getter=getNotificationIds) NSArray* localNotificationIds;
- (void) registerGeneralNotificationCategory;
// List of all notification IDs from given type
- (NSArray*) getNotificationIdsByType:(APPNotificationType)type;
// Find out if notification with ID exists
- (BOOL) notificationExist:(NSNumber*)id;
// Find out if notification with ID and type exists
- (BOOL) notificationExist:(NSNumber*)id type:(APPNotificationType)type;
// Find notification by ID
- (UNNotificationRequest*) getNotificationWithId:(NSNumber*)id;
// Find notification by ID and type
- (UNNotificationRequest*) getNotificationWithId:(NSNumber*)id andType:(APPNotificationType)type;
// Property list from all local notifications
- (NSArray*) getNotificationOptions;
// Property list from given local notifications
- (NSArray*) getNotificationOptionsById:(NSArray*)ids;
// Property list from all local notifications with type constraint
- (NSArray*) getNotificationOptionsByType:(APPNotificationType)type;
// Property list from given local notifications with type constraint
- (NSArray*) getNotificationOptionsByType:(APPNotificationType)type andId:(NSArray*)ids;
// Clear specified notfication
- (void) clearNotification:(UNNotificationRequest*)notification;
// Clear all notfications
- (void) clearAllNotifications;
// Cancel specified notfication
- (void) cancelNotification:(UNNotificationRequest*)notification;
// Cancel all notfications
- (void) cancelAllNotifications;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UNUserNotificationCenter+APPLocalNotification.h"
#import "UNNotificationRequest+APPLocalNotification.h"
@import UserNotifications;
NSString * const kAPPGeneralCategory = @"GENERAL";
@implementation UNUserNotificationCenter (APPLocalNotification)
#pragma mark -
#pragma mark NotificationCategory
/**
* Register general notification category to listen for dismiss actions.
*
* @return [ Void ]
*/
- (void) registerGeneralNotificationCategory
{
UNNotificationCategory* category;
category = [UNNotificationCategory
categoryWithIdentifier:kAPPGeneralCategory
actions:@[]
intentIdentifiers:@[]
options:UNNotificationCategoryOptionCustomDismissAction];
[self setNotificationCategories:[NSSet setWithObjects:category, nil]];
}
#pragma mark -
#pragma mark LocalNotifications
/**
* List of all delivered or still pending notifications.
*/
- (NSArray*) getNotifications
{
NSMutableArray* notifications = [[NSMutableArray alloc] init];
[notifications addObjectsFromArray:[self getPendingNotifications]];
[notifications addObjectsFromArray:[self getDeliveredNotifications]];
return notifications;
}
/**
* List of all triggered notifications.
*/
- (NSArray*) getDeliveredNotifications
{
NSMutableArray* notifications = [[NSMutableArray alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[self getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> *delivered) {
for (UNNotification* notification in delivered) {
[notifications addObject:notification.request];
}
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return notifications;
}
/**
* List of all pending notifications.
*/
- (NSArray*) getPendingNotifications
{
NSMutableArray* notifications = [[NSMutableArray alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[self getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> *requests) {
[notifications addObjectsFromArray:requests];
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return notifications;
}
/**
* List of all notifications from given type.
*
* @param type
* Notification life cycle type
*/
- (NSArray*) getNotificationsByType:(APPNotificationType)type
{
switch (type) {
case NotifcationTypeScheduled:
return [self getPendingNotifications];
case NotifcationTypeTriggered:
return [self getDeliveredNotifications];
default:
return [self getNotifications];
}
}
/**
* List of all local notifications IDs.
*/
- (NSArray*) getNotificationIds
{
NSArray* notifications = [self getNotifications];
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UNNotificationRequest* notification in notifications)
{
[ids addObject:notification.options.id];
}
return ids;
}
/**
* List of all notifications IDs from given type.
*
* @param type
* Notification life cycle type
*/
- (NSArray*) getNotificationIdsByType:(APPNotificationType)type
{
NSArray* notifications = [self getNotificationsByType:type];
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UNNotificationRequest* notification in notifications)
{
[ids addObject:notification.options.id];
}
return ids;
}
/*
* If the notification with the specified ID does exists.
*
* @param id
* Notification ID
*/
- (BOOL) notificationExist:(NSNumber*)id
{
return [self getNotificationWithId:id] != NULL;
}
/* If the notification with specified ID and type exists.
*
* @param id
* Notification ID
* @param type
* Notification life cycle type
*/
- (BOOL) notificationExist:(NSNumber*)id type:(APPNotificationType)type
{
return [self getNotificationWithId:id andType:type] != NULL;
}
/**
* Find notification by ID.
*
* @param id
* Notification ID
*/
- (UNNotificationRequest*) getNotificationWithId:(NSNumber*)id
{
return [self getNotificationWithId:id andType:NotifcationTypeAll];
}
/*
* Find notification by ID and type.
*
* @param id
* Notification ID
* @param type
* Notification life cycle type
*/
- (UNNotificationRequest*) getNotificationWithId:(NSNumber*)id andType:(APPNotificationType)type
{
NSArray* notifications = [self getNotificationsByType:type];
for (UNNotificationRequest* notification in notifications)
{
NSString* fid = [NSString stringWithFormat:@"%@", notification.options.id];
if ([fid isEqualToString:[id stringValue]]) {
return notification;
}
}
return NULL;
}
/**
* List of properties from all notifications.
*/
- (NSArray*) getNotificationOptions
{
return [self getNotificationOptionsByType:NotifcationTypeAll];
}
/**
* List of properties from all notifications of given type.
*
* @param type
* Notification life cycle type
*/
- (NSArray*) getNotificationOptionsByType:(APPNotificationType)type
{
NSArray* notifications = [self getNotificationsByType:type];
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UNNotificationRequest* notification in notifications)
{
[options addObject:notification.options.userInfo];
}
return options;
}
/**
* List of properties from given local notifications.
*
* @param ids
* Notification IDs
*/
- (NSArray*) getNotificationOptionsById:(NSArray*)ids
{
return [self getNotificationOptionsByType:NotifcationTypeAll andId:ids];
}
/**
* List of properties from given local notifications.
*
* @param type
* Notification life cycle type
* @param ids
* Notification IDs
*/
- (NSArray*) getNotificationOptionsByType:(APPNotificationType)type andId:(NSArray*)ids
{
NSArray* notifications = [self getNotificationsByType:type];
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UNNotificationRequest* notification in notifications)
{
if ([ids containsObject:notification.options.id]) {
[options addObject:notification.options.userInfo];
}
}
return options;
}
/*
* Clear all notfications.
*/
- (void) clearAllNotifications
{
[self removeAllDeliveredNotifications];
}
/*
* Clear Specified notfication.
*
* @param notification
* The notification object
*/
- (void) clearNotification:(UNNotificationRequest*)notification
{
NSArray* ids = [[NSArray alloc]
initWithObjects:notification.identifier, nil];
[self removeDeliveredNotificationsWithIdentifiers:ids];
}
/*
* Cancel all notfications.
*/
- (void) cancelAllNotifications
{
[self removeAllPendingNotificationRequests];
[self removeAllDeliveredNotifications];
}
/*
* Cancel specified notfication.
*
* @param notification
* The notification object
*/
- (void) cancelNotification:(UNNotificationRequest*)notification
{
NSArray* ids = [[NSArray alloc]
initWithObjects:notification.identifier, nil];
[self removeDeliveredNotificationsWithIdentifiers:ids];
[self removePendingNotificationRequestsWithIdentifiers:ids];
}
@end
cordova.define("cordova-plugin-local-notifications.LocalNotification.Core", function(require, exports, module) {
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -18,56 +14,60 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Core", func
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
var exec = require('cordova/exec');
/********
* CORE *
********/
/**
* Returns the default settings.
* Request permission to show notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return {Object}
* @return [ Void ]
*/
exports.getDefaults = function () {
return this._defaults;
exports.hasPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
};
/**
* Overwrite default settings.
* Request permission to show notifications.
*
* @param {Object} defaults
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
exports.requestPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
for (var key in defaults) {
if (newDefaults.hasOwnProperty(key)) {
defaults[key] = newDefaults[key];
}
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'request', []);
};
/**
* Schedule a new local notification.
*
* @param {Object} msgs
* The notification properties
* @param {Function} callback
* A function to be called after the notification has been canceled
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (msgs, callback, scope, args) {
var fn = function(granted) {
var fn = function (granted) {
if (!granted) return;
......@@ -86,55 +86,54 @@ exports.schedule = function (msgs, callback, scope, args) {
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.registerPermission(fn, this);
this.requestPermission(fn, this);
}
};
/**
* Update existing notifications specified by IDs in options.
*
* @param {Object} notifications
* The notification properties to update
* @param {Function} callback
* A function to be called after the notification has been updated
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/
exports.update = function (msgs, callback, scope, args) {
var fn = function(granted) {
if (!granted) return;
var notifications = Array.isArray(msgs) ? msgs : [msgs];
for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i];
this.convertProperties(notification);
}
this.exec('update', notifications, callback, scope);
};
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.registerPermission(fn, this);
}
};
// /**
// * Update existing notifications specified by IDs in options.
// *
// * @param {Object} notifications
// * The notification properties to update
// * @param {Function} callback
// * A function to be called after the notification has been updated
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.update = function (msgs, callback, scope, args) {
// var fn = function(granted) {
// if (!granted) return;
// var notifications = Array.isArray(msgs) ? msgs : [msgs];
// for (var i = 0; i < notifications.length; i++) {
// var notification = notifications[i];
// this.convertProperties(notification);
// }
// this.exec('update', notifications, callback, scope);
// };
// if (args && args.skipPermission) {
// fn.call(this, true);
// } else {
// this.registerPermission(fn, this);
// }
// };
/**
* Clear the specified notification.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A function to be called after the notification has been cleared
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
......@@ -144,26 +143,25 @@ exports.clear = function (ids, callback, scope) {
};
/**
* Clear all previously sheduled notifications.
* Clear all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A function to be called after all notifications have been cleared
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.exec('clearAll', null, callback, scope);
};
/**
* Cancel the specified notifications.
*
* @param {String[]} ids
* The IDs of the notifications
* @param {Function} callback
* A function to be called after the notifications has been canceled
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
......@@ -173,69 +171,66 @@ exports.cancel = function (ids, callback, scope) {
};
/**
* Remove all previously registered notifications.
* Cancel all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A function to be called after all notifications have been canceled
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.exec('cancelAll', null, callback, scope);
};
/**
* Check if a notification with an ID is present.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.exec('isPresent', id || 0, callback, scope);
this.exec('isPresent', id, callback, scope);
};
/**
* Check if a notification with an ID is scheduled.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.exec('isScheduled', id || 0, callback, scope);
this.exec('isScheduled', id, callback, scope);
};
/**
* Check if a notification with an ID was triggered.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.exec('isTriggered', id || 0, callback, scope);
this.exec('isTriggered', id, callback, scope);
};
/**
* List all local notification IDs.
* List of all notification ids.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.exec('getAllIds', null, callback, scope);
this.exec('ids', null, callback, scope);
};
/**
......@@ -246,39 +241,38 @@ exports.getIds = function () {
};
/**
* List all scheduled notification IDs.
* List of all scheduled notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.exec('getScheduledIds', null, callback, scope);
this.exec('scheduledIds', null, callback, scope);
};
/**
* List all triggered notification IDs.
* List of all triggered notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.exec('getTriggeredIds', null, callback, scope);
this.exec('triggeredIds', null, callback, scope);
};
/**
* Property list for given local notifications.
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
var args = Array.apply(null, arguments);
......@@ -292,37 +286,36 @@ exports.get = function () {
scope = args[2];
if (!Array.isArray(ids)) {
this.exec('getSingle', Number(ids), callback, scope);
this.exec('notification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getAll', ids, callback, scope);
this.exec('notifications', ids, callback, scope);
};
/**
* Property list for all local notifications.
* List for all notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.exec('getAll', null, callback, scope);
this.exec('notifications', null, callback, scope);
};
/**
* Property list for given scheduled notifications.
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function () {
var args = Array.apply(null, arguments);
......@@ -340,37 +333,34 @@ exports.getScheduled = function () {
}
if (!Array.isArray(ids)) {
this.exec('getSingleScheduled', Number(ids), callback, scope);
this.exec('scheduledNotification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getScheduled', ids, callback, scope);
this.exec('scheduledNotifications', ids, callback, scope);
};
/**
* Property list for all scheduled notifications.
* List of all scheduled notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.exec('getScheduled', null, callback, scope);
this.exec('scheduledNotifications', null, callback, scope);
};
/**
* Property list for given triggered notifications.
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function () {
var args = Array.apply(null, arguments);
......@@ -388,86 +378,59 @@ exports.getTriggered = function () {
}
if (!Array.isArray(ids)) {
this.exec('getSingleTriggered', Number(ids), callback, scope);
this.exec('triggeredNotification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getTriggered', ids, callback, scope);
this.exec('triggeredNotifications', ids, callback, scope);
};
/**
* Property list for all triggered notifications.
* List of all triggered notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.exec('getTriggered', null, callback, scope);
this.exec('triggeredNotifications', null, callback, scope);
};
/**
* Informs if the app has the permission to show notifications.
* The (platform specific) default settings.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Object ]
*/
exports.hasPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
exports.getDefaults = function () {
return this._defaults;
};
/**
* Register permission to show notifications if not already granted.
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Void ]
*/
exports.requestPermission = function (callback, scope) {
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
if (this._registered) {
return this.hasPermission(callback, scope);
} else {
this._registered = true;
for (var key in defaults) {
if (newDefaults.hasOwnProperty(key)) {
defaults[key] = newDefaults[key];
}
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'request', []);
};
/**********
* EVENTS *
**********/
/**
* Register callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param {Object?} scope
* The callback function's scope
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
......@@ -486,10 +449,10 @@ exports.on = function (event, callback, scope) {
/**
* Unregister callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
var listener = this._listener[event];
......
cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", function(require, exports, module) {
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -18,18 +14,11 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", func
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
var exec = require('cordova/exec'),
channel = require('cordova/channel');
/***********
* MEMBERS *
***********/
// Default values
exports._defaults = {
text: '',
......@@ -42,22 +31,13 @@ exports._defaults = {
at: undefined
};
// listener
// Listener
exports._listener = {};
// Registered permission flag
exports._registered = false;
/********
* UTIL *
********/
/**
* Merge platform specific properties into the default ones.
*
* @return {Object}
* The default properties for the platform
* @return [ Void ]
*/
exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults;
......@@ -71,19 +51,18 @@ exports.applyPlatformSpecificOptions = function () {
defaults.led = undefined;
defaults.color = undefined;
break;
case 'iOS':
defaults.attachments = undefined;
break;
}
return defaults;
};
/**
* Merge custom properties with the default values.
*
* @param {Object} options
* Set of custom values
* @param [ Object ] options Set of custom values.
*
* @retrun {Object}
* The merged property list
* @retrun [ Object ]
*/
exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults();
......@@ -127,11 +106,9 @@ exports.mergeWithDefaults = function (options) {
/**
* Convert the passed values to their required type.
*
* @param {Object} options
* Set of custom values
* @param [ Object ] options Properties to convert for.
*
* @retrun {Object}
* The converted property list
* @return [ Object ] The converted property list
*/
exports.convertProperties = function (options) {
......@@ -173,46 +150,33 @@ exports.convertProperties = function (options) {
options.data = JSON.stringify(options.data);
}
if (options.every) {
if (device.platform == 'iOS' && typeof options.every != 'string') {
options.every = this.getDefaults().every;
var warning = 'Every option is not a string: ' + options.id;
warning += '. Expects one of: second, minute, hour, day, week, ';
warning += 'month, year on iOS.';
console.warn(warning);
}
}
return options;
};
/**
* Create callback, which will be executed within a specific scope.
* Create a callback function to get executed within a specific scope.
*
* @param {Function} callbackFn
* The callback function
* @param {Object} scope
* The scope for the function
* @param [ Function ] fn The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return {Function}
* The new callback function
* @return [ Function ]
*/
exports.createCallbackFn = function (callbackFn, scope) {
exports.createCallbackFn = function (fn, scope) {
if (typeof callbackFn != 'function')
if (typeof fn != 'function')
return;
return function () {
callbackFn.apply(scope || this, arguments);
fn.apply(scope || this, arguments);
};
};
/**
* Convert the IDs to numbers.
*
* @param {String/Number[]} ids
* @param [ Array ] ids
*
* @return Array of Numbers
* @return [ Array<Number> ]
*/
exports.convertIds = function (ids) {
var convertedIds = [];
......@@ -227,10 +191,10 @@ exports.convertIds = function (ids) {
/**
* First found value for the given keys.
*
* @param {Object} options
* Object with key-value properties
* @param {String[]} keys*
* Key list
* @param [ Object ] options Object with key-value properties.
* @param [ *Array<String> ] keys List of keys.
*
* @return [ Object ]
*/
exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1);
......@@ -245,12 +209,12 @@ exports.getValueFor = function (options) {
};
/**
* Fire event with given arguments.
* Fire the event with given arguments.
*
* @param {String} event
* The event's name
* @param {args*}
* The callback's arguments
* @param [ String ] event The event's name.
* @param [ *Array] args The callback's arguments.
*
* @return [ Void]
*/
exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1),
......@@ -270,14 +234,12 @@ exports.fireEvent = function (event) {
/**
* Execute the native counterpart.
*
* @param {String} action
* The name of the action
* @param args[]
* Array of arguments
* @param {Function} callback
* The callback function
* @param {Object} scope
* The scope for the function
* @param [ String ] action The name of the action.
* @param [ Array ] args Array of arguments.
* @param [ Function] callback The callback function.
* @param [ Object ] scope The scope for the function.
*
* @return [ Void ]
*/
exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope),
......@@ -292,11 +254,6 @@ exports.exec = function (action, args, callback, scope) {
exec(fn, null, 'LocalNotification', action, params);
};
/*********
* HOOKS *
*********/
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered
......
cordova.define("cordova-plugin-local-notifications.LocalNotification", function(require, exports, module) {
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -18,192 +14,159 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification", function(
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
/*************
* INTERFACE *
*************/
/**
* Returns the default settings.
* Request permission to show notifications.
*
* @return {Object}
*/
exports.getDefaults = function () {
return this.core.getDefaults();
};
/**
* Overwrite default settings.
*
* @param {Object} defaults
*/
exports.setDefaults = function (defaults) {
this.core.setDefaults(defaults);
};
/**
* Informs if the app has the permission to show notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Void ]
*/
exports.hasPermission = function (callback, scope) {
this.core.hasPermission(callback, scope);
};
/**
* Register permission to show notifications if not already granted.
* Request permission to show notifications.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope);
};
/**
* Schedule a new local notification.
*
* @param {Object} notifications
* The notification properties
* @param {Function} callback
* A function to be called after the notification has been canceled
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (notifications, callback, scope, args) {
this.core.schedule(notifications, callback, scope, args);
};
/**
* Update existing notifications specified by IDs in options.
*
* @param {Object} notifications
* The notification properties to update
* @param {Function} callback
* A function to be called after the notification has been updated
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/
exports.update = function (notifications, callback, scope, args) {
this.core.update(notifications, callback, scope, args);
};
// /**
// * Update existing notifications specified by IDs in options.
// *
// * @param {Object} notifications
// * The notification properties to update
// * @param {Function} callback
// * A function to be called after the notification has been updated
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.update = function (notifications, callback, scope, args) {
// this.core.update(notifications, callback, scope, args);
// };
/**
* Clear the specified notification.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A function to be called after the notification has been cleared
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
this.core.clear(ids, callback, scope);
};
/**
* Clear all previously sheduled notifications.
* Clear all triggered notifications.
*
* @param {Function} callback
* A function to be called after all notifications have been cleared
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.core.clearAll(callback, scope);
};
/**
* Cancel the specified notifications.
*
* @param {String[]} ids
* The IDs of the notifications
* @param {Function} callback
* A function to be called after the notifications has been canceled
* @param {Object?} scope
* The scope for the callback function
* Cancel the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
this.core.cancel(ids, callback, scope);
};
/**
* Remove all previously registered notifications.
* Cancel all scheduled notifications.
*
* @param {Function} callback
* A function to be called after all notifications have been canceled
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.core.cancelAll(callback, scope);
};
/**
* Check if a notification with an ID is present.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.core.isPresent(id, callback, scope);
};
/**
* Check if a notification with an ID is scheduled.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.core.isScheduled(id, callback, scope);
};
/**
* Check if a notification with an ID was triggered.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.core.isTriggered(id, callback, scope);
};
/**
* List all local notification IDs.
* List of all notification ids.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.core.getAllIds(callback, scope);
......@@ -217,148 +180,131 @@ exports.getIds = function () {
};
/**
* List all scheduled notification IDs.
* List of all scheduled notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.core.getScheduledIds(callback, scope);
};
/**
* List all triggered notification IDs.
* List of all triggered notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.core.getTriggeredIds(callback, scope);
};
/**
* Property list for given local notifications.
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
this.core.get.apply(this.core, arguments);
exports.get = function (ids, callback, scope) {
this.core.get(ids, callback, scope);
};
/**
* Property list for all local notifications.
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.core.getAll(callback, scope);
};
/**
* Property list for given scheduled notifications.
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function () {
this.core.getScheduled.apply(this.core, arguments);
exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled(ids, callback, scope);
};
/**
* Property list for all scheduled notifications.
* List of all scheduled notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.core.getAllScheduled(callback, scope);
};
/**
* Property list for given triggered notifications.
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function () {
this.core.getTriggered.apply(this.core, arguments);
exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered(ids, callback, scope);
};
/**
* Property list for all triggered notifications.
* List of all triggered notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.core.getAllTriggered(callback, scope);
};
/****************
* DEPRECATIONS *
****************/
/**
* Schedule a new local notification.
* The (platform specific) default settings.
*
* @return [ Object ]
*/
exports.add = function () {
console.warn('Depreated: Please use `notification.local.schedule` instead.');
this.schedule.apply(this, arguments);
exports.getDefaults = function () {
return this.core.getDefaults();
};
/**
* Register permission to show notifications
* if not already granted.
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.promptForPermission = function () {
console.warn('Depreated: Please use `notification.local.registerPermission` instead.');
this.registerPermission.apply(this, arguments);
exports.setDefaults = function (defaults) {
this.core.setDefaults(defaults);
};
/**********
* EVENTS *
**********/
/**
* Register callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param {Object?} scope
* The callback function's scope
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
this.core.on(event, callback, scope);
......@@ -367,10 +313,10 @@ exports.on = function (event, callback, scope) {
/**
* Unregister callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
this.core.un(event, callback);
......
......@@ -30,7 +30,7 @@
<body>
<div>
<div class="app">
<h1>Local Notification Example</h1>
<h1>Notification Example</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
......@@ -47,7 +47,7 @@
<a id="sched_multi" class="button orange">Multiple</a>
</div>
<div class="container">
<a id="sched_delay" class="button orange">Delayed</a>
<a id="sched_delayed" class="button orange">Delayed</a>
<a id="sched_interval" class="button orange">Interval</a>
</div>
<h2 class="section">Update</h2>
......@@ -85,7 +85,7 @@
<a id="triggered_ids" class="button grey">Triggered</a>
</div>
<div class="container">
<a id="all_ids" class="button grey">All</a>
<a id="ids" class="button grey">All</a>
</div>
<h2 class="section">Notifications</h2>
<div class="container">
......@@ -93,11 +93,11 @@
<a id="triggered_nots" class="button grey">Triggered</a>
</div>
<div class="container">
<a id="single_not" class="button grey">Single</a>
<a id="notification" class="button grey">Single</a>
<a id="multiple_nots" class="button grey">Multiple</a>
</div>
<div class="container">
<a id="all_nots" class="button grey">All</a>
<a id="notifications" class="button grey">All</a>
</div>
<h2 class="section">Defaults</h2>
<div class="container">
......
......@@ -36,6 +36,7 @@ var app = {
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.pluginInitialize();
app.bindNotificationEvents();
},
// Update DOM on a Received Event
receivedEvent: function(id) {
......@@ -52,14 +53,238 @@ var app = {
pluginInitialize: function() {
document.getElementById('granted').onclick = app.hasPermission;
document.getElementById('request').onclick = app.askPermission;
document.getElementById('sched_single').onclick = app.scheduleSingle;
document.getElementById('sched_multi').onclick = app.scheduleMultiple;
document.getElementById('sched_delayed').onclick = app.scheduleDelayed;
document.getElementById('sched_interval').onclick = app.scheduleInterval;
document.getElementById('clear_single').onclick = app.clearSingle;
document.getElementById('clear_multi').onclick = app.clearMulti;
document.getElementById('clear_all').onclick = app.clearAll;
document.getElementById('cancel_single').onclick = app.cancelSingle;
document.getElementById('cancel_multi').onclick = app.cancelMulti;
document.getElementById('cancel_all').onclick = app.cancelAll;
document.getElementById('present?').onclick = app.isPresent;
document.getElementById('scheduled?').onclick = app.isScheduled;
document.getElementById('triggered?').onclick = app.isTriggered;
document.getElementById('ids').onclick = app.ids;
document.getElementById('scheduled_ids').onclick = app.scheduledIds;
document.getElementById('triggered_ids').onclick = app.triggeredIds;
document.getElementById('scheduled_nots').onclick = app.scheduledNots;
document.getElementById('triggered_nots').onclick = app.triggeredNots;
document.getElementById('notification').onclick = app.notification;
document.getElementById('multiple_nots').onclick = app.multipleNots;
document.getElementById('notifications').onclick = app.notifications;
document.getElementById('defaults').onclick = app.setDefaultTitle;
},
// Check permissions to read accounts
hasPermission: function () {
cordova.plugins.notification.local.hasPermission(showToast);
cordova.plugins.notification.local.hasPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
},
// Request permissions to read accounts
askPermission: function () {
cordova.plugins.notification.local.requestPermission(showToast);
cordova.plugins.notification.local.requestPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
},
// Schedule a single notification
scheduleSingle: function () {
cordova.plugins.notification.local.schedule({
id: 1,
text: 'Test Message 1',
icon: 'http://3.bp.blogspot.com/-Qdsy-GpempY/UU_BN9LTqSI/AAAAAAAAAMA/LkwLW2yNBJ4/s1600/supersu.png',
smallIcon: 'res://cordova',
attachments: ['file://img/logo.png'],
sound: null,
badge: 1,
data: { test: 1 }
});
},
// Schedule multiple notifications at once
scheduleMultiple: function () {
cordova.plugins.notification.local.schedule([{
id: 1,
text: 'Multi Message 1',
icon: 'res://cordova'
}, {
id: 2,
text: 'Multi Message 2',
icon: 'res://icon',
smallIcon: 'ic_media_play'
}, {
id: 3,
text: 'Multi Message 3',
icon: 'res://icon',
smallIcon: 'ic_media_pause'
}]);
},
// Schedule a delayed notification
scheduleDelayed: function () {
var now = new Date().getTime(),
_5_sec_from_now = new Date(now + 5 * 1000);
var sound = device.platform == 'Android' ? 'file://sound.mp3' : 'file://beep.caf';
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Scheduled with delay',
text: 'Test Message 1',
at: _5_sec_from_now,
sound: sound,
badge: 12
});
},
// Schedule a repeating notification
scheduleInterval: function () {
var sound = device.platform == 'Android' ? 'file://sound.mp3' : 'file://beep.caf';
cordova.plugins.notification.local.schedule({
id: 1,
text: 'Scheduled every minute',
every: 'minute',
sound: sound,
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
},
// Clear a single notification
clearSingle: function () {
cordova.plugins.notification.local.clear(1, app.ids);
},
// Clear multiple notifications
clearMulti: function () {
cordova.plugins.notification.local.clear([2, 3], app.ids);
},
// Clear all notifications
clearAll: function () {
cordova.plugins.notification.local.clearAll(app.ids);
},
// Clear a single notification
cancelSingle: function () {
cordova.plugins.notification.local.cancel(1, app.ids);
},
// Clear multiple notifications
cancelMulti: function () {
cordova.plugins.notification.local.cancel([2, 3], app.ids);
},
// Cancel all notifications
cancelAll: function () {
cordova.plugins.notification.local.cancelAll(app.ids);
},
// If the notifcation is scheduled or triggered
isPresent: function () {
cordova.plugins.notification.local.isPresent(1, function (present) {
showToast(present ? 'Yes' : 'No');
});
},
// If the notifcation is scheduled
isScheduled: function () {
cordova.plugins.notification.local.isScheduled(1, function (scheduled) {
showToast(scheduled ? 'Yes' : 'No');
});
},
// If the notifcation is triggered
isTriggered: function () {
cordova.plugins.notification.local.isTriggered(1, function (triggered) {
showToast(triggered ? 'Yes' : 'No');
});
},
// Get all notification ids
ids: function () {
cordova.plugins.notification.local.getIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all notification ids
scheduledIds: function () {
cordova.plugins.notification.local.getScheduledIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all notification ids
triggeredIds: function () {
cordova.plugins.notification.local.getTriggeredIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all scheduled notifications
scheduledNots: function () {
cordova.plugins.notification.local.getAllScheduled(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get all triggered notifications
triggeredNots: function () {
cordova.plugins.notification.local.getAllTriggered(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get a single notification
notification: function () {
cordova.plugins.notification.local.get(1, function (obj) {
console.log(obj);
showToast(obj ? obj.toString() : '- none -');
});
},
// Get multiple notifications
multipleNots: function () {
cordova.plugins.notification.local.get([1, 2], function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get all notifications
notifications: function () {
cordova.plugins.notification.local.getAll(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Set another default title
setDefaultTitle: function () {
cordova.plugins.notification.local.setDefaults({ title: 'New Default Title' });
showToast('New Default Title');
},
// Listen for events
bindNotificationEvents: function () {
cordova.plugins.notification.local.on('schedule', function (obj) {
console.log('onschedule', arguments);
// showToast('scheduled: ' + obj.id);
});
cordova.plugins.notification.local.on('update', function (obj) {
console.log('onupdate', arguments);
// showToast('updated: ' + obj.id);
});
cordova.plugins.notification.local.on('trigger', function (obj) {
console.log('ontrigger', arguments);
showToast('triggered: ' + obj.id);
});
cordova.plugins.notification.local.on('click', function (obj) {
console.log('onclick', arguments);
showToast('clicked: ' + obj.id);
});
cordova.plugins.notification.local.on('cancel', function (obj) {
console.log('oncancel', arguments);
// showToast('canceled: ' + obj.id);
});
cordova.plugins.notification.local.on('clear', function (obj) {
console.log('onclear', arguments);
showToast('cleared: ' + obj.id);
});
cordova.plugins.notification.local.on('cancelall', function () {
console.log('oncancelall', arguments);
// showToast('canceled all');
});
cordova.plugins.notification.local.on('clearall', function () {
console.log('onclearall', arguments);
// showToast('cleared all');
});
}
};
......
......@@ -56,66 +56,39 @@ exports.requestPermission = function (callback, scope) {
exec(fn, null, 'LocalNotification', 'request', []);
};
// /**
// * Returns the default settings.
// *
// * @return {Object}
// */
// exports.getDefaults = function () {
// return this._defaults;
// };
// /**
// * Overwrite default settings.
// *
// * @param {Object} defaults
// */
// exports.setDefaults = function (newDefaults) {
// var defaults = this.getDefaults();
// for (var key in defaults) {
// if (newDefaults.hasOwnProperty(key)) {
// defaults[key] = newDefaults[key];
// }
// }
// };
// /**
// * Schedule a new local notification.
// *
// * @param {Object} msgs
// * The notification properties
// * @param {Function} callback
// * A function to be called after the notification has been canceled
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.schedule = function (msgs, callback, scope, args) {
// var fn = function(granted) {
/**
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (msgs, callback, scope, args) {
var fn = function (granted) {
// if (!granted) return;
if (!granted) return;
// var notifications = Array.isArray(msgs) ? msgs : [msgs];
var notifications = Array.isArray(msgs) ? msgs : [msgs];
// for (var i = 0; i < notifications.length; i++) {
// var notification = notifications[i];
for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i];
// this.mergeWithDefaults(notification);
// this.convertProperties(notification);
// }
this.mergeWithDefaults(notification);
this.convertProperties(notification);
}
// this.exec('schedule', notifications, callback, scope);
// };
this.exec('schedule', notifications, callback, scope);
};
// if (args && args.skipPermission) {
// fn.call(this, true);
// } else {
// this.registerPermission(fn, this);
// }
// };
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.requestPermission(fn, this);
}
};
// /**
// * Update existing notifications specified by IDs in options.
......@@ -153,340 +126,348 @@ exports.requestPermission = function (callback, scope) {
// }
// };
// /**
// * Clear the specified notification.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A function to be called after the notification has been cleared
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.clear = function (ids, callback, scope) {
// ids = Array.isArray(ids) ? ids : [ids];
// ids = this.convertIds(ids);
/**
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
ids = this.convertIds(ids);
// this.exec('clear', ids, callback, scope);
// };
this.exec('clear', ids, callback, scope);
};
// /**
// * Clear all previously sheduled notifications.
// *
// * @param {Function} callback
// * A function to be called after all notifications have been cleared
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.clearAll = function (callback, scope) {
// this.exec('clearAll', null, callback, scope);
// };
/**
* Clear all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.exec('clearAll', null, callback, scope);
};
// /**
// * Cancel the specified notifications.
// *
// * @param {String[]} ids
// * The IDs of the notifications
// * @param {Function} callback
// * A function to be called after the notifications has been canceled
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.cancel = function (ids, callback, scope) {
// ids = Array.isArray(ids) ? ids : [ids];
// ids = this.convertIds(ids);
/**
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
ids = this.convertIds(ids);
// this.exec('cancel', ids, callback, scope);
// };
this.exec('cancel', ids, callback, scope);
};
// /**
// * Remove all previously registered notifications.
// *
// * @param {Function} callback
// * A function to be called after all notifications have been canceled
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.cancelAll = function (callback, scope) {
// this.exec('cancelAll', null, callback, scope);
// };
/**
* Cancel all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.exec('cancelAll', null, callback, scope);
};
// /**
// * Check if a notification with an ID is present.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.isPresent = function (id, callback, scope) {
// this.exec('isPresent', id || 0, callback, scope);
// };
/**
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.exec('isPresent', id, callback, scope);
};
// /**
// * Check if a notification with an ID is scheduled.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.isScheduled = function (id, callback, scope) {
// this.exec('isScheduled', id || 0, callback, scope);
// };
/**
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.exec('isScheduled', id, callback, scope);
};
// /**
// * Check if a notification with an ID was triggered.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.isTriggered = function (id, callback, scope) {
// this.exec('isTriggered', id || 0, callback, scope);
// };
/**
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.exec('isTriggered', id, callback, scope);
};
// *
// * List all local notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
/**
* List of all notification ids.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.exec('ids', null, callback, scope);
};
// exports.getAllIds = function (callback, scope) {
// this.exec('getAllIds', null, callback, scope);
// };
/**
* Alias for `getAllIds`.
*/
exports.getIds = function () {
this.getAllIds.apply(this, arguments);
};
// /**
// * Alias for `getAllIds`.
// */
// exports.getIds = function () {
// this.getAllIds.apply(this, arguments);
// };
/**
* List of all scheduled notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.exec('scheduledIds', null, callback, scope);
};
// /**
// * List all scheduled notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getScheduledIds = function (callback, scope) {
// this.exec('getScheduledIds', null, callback, scope);
// };
/**
* List of all triggered notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.exec('triggeredIds', null, callback, scope);
};
// /**
// * List all triggered notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getTriggeredIds = function (callback, scope) {
// this.exec('getTriggeredIds', null, callback, scope);
// };
/**
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
var args = Array.apply(null, arguments);
// /**
// * Property list for given local notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.get = function () {
// var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
// if (typeof args[0] == 'function') {
// args.unshift([]);
// }
var ids = args[0],
callback = args[1],
scope = args[2];
// var ids = args[0],
// callback = args[1],
// scope = args[2];
if (!Array.isArray(ids)) {
this.exec('notification', Number(ids), callback, scope);
return;
}
// if (!Array.isArray(ids)) {
// this.exec('getSingle', Number(ids), callback, scope);
// return;
// }
ids = this.convertIds(ids);
// ids = this.convertIds(ids);
this.exec('notifications', ids, callback, scope);
};
// this.exec('getAll', ids, callback, scope);
// };
/**
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.exec('notifications', null, callback, scope);
};
// /**
// * Property list for all local notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAll = function (callback, scope) {
// this.exec('getAll', null, callback, scope);
// };
/**
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function () {
var args = Array.apply(null, arguments);
// /**
// * Property list for given scheduled notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getScheduled = function () {
// var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
// if (typeof args[0] == 'function') {
// args.unshift([]);
// }
var ids = args[0],
callback = args[1],
scope = args[2];
// var ids = args[0],
// callback = args[1],
// scope = args[2];
if (!Array.isArray(ids)) {
ids = [ids];
}
// if (!Array.isArray(ids)) {
// ids = [ids];
// }
if (!Array.isArray(ids)) {
this.exec('scheduledNotification', Number(ids), callback, scope);
return;
}
// if (!Array.isArray(ids)) {
// this.exec('getSingleScheduled', Number(ids), callback, scope);
// return;
// }
ids = this.convertIds(ids);
// ids = this.convertIds(ids);
this.exec('scheduledNotifications', ids, callback, scope);
};
// this.exec('getScheduled', ids, callback, scope);
// };
/**
* List of all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.exec('scheduledNotifications', null, callback, scope);
};
// /**
// * Property list for all scheduled notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAllScheduled = function (callback, scope) {
// this.exec('getScheduled', null, callback, scope);
// };
/**
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function () {
var args = Array.apply(null, arguments);
// /**
// * Property list for given triggered notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getTriggered = function () {
// var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
// if (typeof args[0] == 'function') {
// args.unshift([]);
// }
var ids = args[0],
callback = args[1],
scope = args[2];
// var ids = args[0],
// callback = args[1],
// scope = args[2];
if (!Array.isArray(ids)) {
ids = [ids];
}
// if (!Array.isArray(ids)) {
// ids = [ids];
// }
if (!Array.isArray(ids)) {
this.exec('triggeredNotification', Number(ids), callback, scope);
return;
}
// if (!Array.isArray(ids)) {
// this.exec('getSingleTriggered', Number(ids), callback, scope);
// return;
// }
ids = this.convertIds(ids);
// ids = this.convertIds(ids);
this.exec('triggeredNotifications', ids, callback, scope);
};
// this.exec('getTriggered', ids, callback, scope);
// };
/**
* List of all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.exec('triggeredNotifications', null, callback, scope);
};
// /**
// * Property list for all triggered notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAllTriggered = function (callback, scope) {
// this.exec('getTriggered', null, callback, scope);
// };
/**
* The (platform specific) default settings.
*
* @return [ Object ]
*/
exports.getDefaults = function () {
return this._defaults;
};
/**
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
// /**********
// * EVENTS *
// **********/
for (var key in defaults) {
if (newDefaults.hasOwnProperty(key)) {
defaults[key] = newDefaults[key];
}
}
};
// /**
// * Register callback for given event.
// *
// * @param {String} event
// * The event's name
// * @param {Function} callback
// * The function to be exec as callback
// * @param {Object?} scope
// * The callback function's scope
// */
// exports.on = function (event, callback, scope) {
/**
* Register callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
// if (typeof callback !== "function")
// return;
if (typeof callback !== "function")
return;
// if (!this._listener[event]) {
// this._listener[event] = [];
// }
if (!this._listener[event]) {
this._listener[event] = [];
}
// var item = [callback, scope || window];
var item = [callback, scope || window];
// this._listener[event].push(item);
// };
this._listener[event].push(item);
};
// /**
// * Unregister callback for given event.
// *
// * @param {String} event
// * The event's name
// * @param {Function} callback
// * The function to be exec as callback
// */
// exports.un = function (event, callback) {
// var listener = this._listener[event];
/**
* Unregister callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
var listener = this._listener[event];
// if (!listener)
// return;
if (!listener)
return;
// for (var i = 0; i < listener.length; i++) {
// var fn = listener[i][0];
for (var i = 0; i < listener.length; i++) {
var fn = listener[i][0];
// if (fn == callback) {
// listener.splice(i, 1);
// break;
// }
// }
// };
if (fn == callback) {
listener.splice(i, 1);
break;
}
}
};
});
......@@ -15,166 +15,143 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", func
* Please see the License for the specific language governing rights and
* limitations under the License.
*/
// var exec = require('cordova/exec'),
// channel = require('cordova/channel');
// /***********
// * MEMBERS *
// ***********/
// // Default values
// exports._defaults = {
// text: '',
// title: '',
// sound: 'res://platform_default',
// badge: 0,
// id: 0,
// data: undefined,
// every: undefined,
// at: undefined
// };
// // listener
// exports._listener = {};
// /********
// * UTIL *
// ********/
// /**
// * Merge platform specific properties into the default ones.
// *
// * @return {Object}
// * The default properties for the platform
// */
// exports.applyPlatformSpecificOptions = function () {
// var defaults = this._defaults;
// switch (device.platform) {
// case 'Android':
// defaults.icon = 'res://ic_popup_reminder';
// defaults.smallIcon = undefined;
// defaults.ongoing = false;
// defaults.autoClear = true;
// defaults.led = undefined;
// defaults.color = undefined;
// break;
// }
// return defaults;
// };
// /**
// * Merge custom properties with the default values.
// *
// * @param {Object} options
// * Set of custom values
// *
// * @retrun {Object}
// * The merged property list
// */
// exports.mergeWithDefaults = function (options) {
// var defaults = this.getDefaults();
// options.at = this.getValueFor(options, 'at', 'firstAt', 'date');
// options.text = this.getValueFor(options, 'text', 'message');
// options.data = this.getValueFor(options, 'data', 'json');
// if (defaults.hasOwnProperty('autoClear')) {
// options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
// }
// if (options.autoClear !== true && options.ongoing) {
// options.autoClear = false;
// }
// if (options.at === undefined || options.at === null) {
// options.at = new Date();
// }
// for (var key in defaults) {
// if (options[key] === null || options[key] === undefined) {
// if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
// options[key] = undefined;
// } else {
// options[key] = defaults[key];
// }
// }
// }
// for (key in options) {
// if (!defaults.hasOwnProperty(key)) {
// delete options[key];
// console.warn('Unknown property: ' + key);
// }
// }
// return options;
// };
// /**
// * Convert the passed values to their required type.
// *
// * @param {Object} options
// * Set of custom values
// *
// * @retrun {Object}
// * The converted property list
// */
// exports.convertProperties = function (options) {
// if (options.id) {
// if (isNaN(options.id)) {
// options.id = this.getDefaults().id;
// console.warn('Id is not a number: ' + options.id);
// } else {
// options.id = Number(options.id);
// }
// }
// if (options.title) {
// options.title = options.title.toString();
// }
// if (options.text) {
// options.text = options.text.toString();
// }
// if (options.badge) {
// if (isNaN(options.badge)) {
// options.badge = this.getDefaults().badge;
// console.warn('Badge number is not a number: ' + options.id);
// } else {
// options.badge = Number(options.badge);
// }
// }
// if (options.at) {
// if (typeof options.at == 'object') {
// options.at = options.at.getTime();
// }
// options.at = Math.round(options.at/1000);
// }
// if (typeof options.data == 'object') {
// options.data = JSON.stringify(options.data);
// }
// if (options.every) {
// if (device.platform == 'iOS' && typeof options.every != 'string') {
// options.every = this.getDefaults().every;
// var warning = 'Every option is not a string: ' + options.id;
// warning += '. Expects one of: second, minute, hour, day, week, ';
// warning += 'month, year on iOS.';
// console.warn(warning);
// }
// }
// return options;
// };
var exec = require('cordova/exec'),
channel = require('cordova/channel');
// Default values
exports._defaults = {
text: '',
title: '',
sound: 'res://platform_default',
badge: 0,
id: 0,
data: undefined,
every: undefined,
at: undefined
};
// Listener
exports._listener = {};
/**
* Merge platform specific properties into the default ones.
*
* @return [ Void ]
*/
exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults;
switch (device.platform) {
case 'Android':
defaults.icon = 'res://ic_popup_reminder';
defaults.smallIcon = undefined;
defaults.ongoing = false;
defaults.autoClear = true;
defaults.led = undefined;
defaults.color = undefined;
break;
case 'iOS':
defaults.attachments = undefined;
break;
}
};
/**
* Merge custom properties with the default values.
*
* @param [ Object ] options Set of custom values.
*
* @retrun [ Object ]
*/
exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults();
options.at = this.getValueFor(options, 'at', 'firstAt', 'date');
options.text = this.getValueFor(options, 'text', 'message');
options.data = this.getValueFor(options, 'data', 'json');
if (defaults.hasOwnProperty('autoClear')) {
options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
}
if (options.autoClear !== true && options.ongoing) {
options.autoClear = false;
}
if (options.at === undefined || options.at === null) {
options.at = new Date();
}
for (var key in defaults) {
if (options[key] === null || options[key] === undefined) {
if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
options[key] = undefined;
} else {
options[key] = defaults[key];
}
}
}
for (key in options) {
if (!defaults.hasOwnProperty(key)) {
delete options[key];
console.warn('Unknown property: ' + key);
}
}
return options;
};
/**
* Convert the passed values to their required type.
*
* @param [ Object ] options Properties to convert for.
*
* @return [ Object ] The converted property list
*/
exports.convertProperties = function (options) {
if (options.id) {
if (isNaN(options.id)) {
options.id = this.getDefaults().id;
console.warn('Id is not a number: ' + options.id);
} else {
options.id = Number(options.id);
}
}
if (options.title) {
options.title = options.title.toString();
}
if (options.text) {
options.text = options.text.toString();
}
if (options.badge) {
if (isNaN(options.badge)) {
options.badge = this.getDefaults().badge;
console.warn('Badge number is not a number: ' + options.id);
} else {
options.badge = Number(options.badge);
}
}
if (options.at) {
if (typeof options.at == 'object') {
options.at = options.at.getTime();
}
options.at = Math.round(options.at/1000);
}
if (typeof options.data == 'object') {
options.data = JSON.stringify(options.data);
}
return options;
};
/**
* Create a callback function to get executed within a specific scope.
......@@ -194,110 +171,103 @@ exports.createCallbackFn = function (fn, scope) {
};
};
// /**
// * Convert the IDs to numbers.
// *
// * @param {String/Number[]} ids
// *
// * @return Array of Numbers
// */
// exports.convertIds = function (ids) {
// var convertedIds = [];
// for (var i = 0; i < ids.length; i++) {
// convertedIds.push(Number(ids[i]));
// }
// return convertedIds;
// };
// /**
// * First found value for the given keys.
// *
// * @param {Object} options
// * Object with key-value properties
// * @param {String[]} keys*
// * Key list
// */
// exports.getValueFor = function (options) {
// var keys = Array.apply(null, arguments).slice(1);
// for (var i = 0; i < keys.length; i++) {
// var key = keys[i];
// if (options.hasOwnProperty(key)) {
// return options[key];
// }
// }
// };
// /**
// * Fire event with given arguments.
// *
// * @param {String} event
// * The event's name
// * @param {args*}
// * The callback's arguments
// */
// exports.fireEvent = function (event) {
// var args = Array.apply(null, arguments).slice(1),
// listener = this._listener[event];
// if (!listener)
// return;
// for (var i = 0; i < listener.length; i++) {
// var fn = listener[i][0],
// scope = listener[i][1];
// fn.apply(scope, args);
// }
// };
// /**
// * Execute the native counterpart.
// *
// * @param {String} action
// * The name of the action
// * @param args[]
// * Array of arguments
// * @param {Function} callback
// * The callback function
// * @param {Object} scope
// * The scope for the function
// */
// exports.exec = function (action, args, callback, scope) {
// var fn = this.createCallbackFn(callback, scope),
// params = [];
// if (Array.isArray(args)) {
// params = args;
// } else if (args) {
// params.push(args);
// }
// exec(fn, null, 'LocalNotification', action, params);
// };
// /*********
// * HOOKS *
// *********/
// // Called after 'deviceready' event
// channel.deviceready.subscribe(function () {
// // Device is ready now, the listeners are registered
// // and all queued events can be executed.
// exec(null, null, 'LocalNotification', 'deviceready', []);
// });
// // Called before 'deviceready' event
// channel.onCordovaReady.subscribe(function () {
// // Device plugin is ready now
// channel.onCordovaInfoReady.subscribe(function () {
// // Merge platform specifics into defaults
// exports.applyPlatformSpecificOptions();
// });
// });
/**
* Convert the IDs to numbers.
*
* @param [ Array ] ids
*
* @return [ Array<Number> ]
*/
exports.convertIds = function (ids) {
var convertedIds = [];
for (var i = 0; i < ids.length; i++) {
convertedIds.push(Number(ids[i]));
}
return convertedIds;
};
/**
* First found value for the given keys.
*
* @param [ Object ] options Object with key-value properties.
* @param [ *Array<String> ] keys List of keys.
*
* @return [ Object ]
*/
exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (options.hasOwnProperty(key)) {
return options[key];
}
}
};
/**
* Fire the event with given arguments.
*
* @param [ String ] event The event's name.
* @param [ *Array] args The callback's arguments.
*
* @return [ Void]
*/
exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1),
listener = this._listener[event];
if (!listener)
return;
for (var i = 0; i < listener.length; i++) {
var fn = listener[i][0],
scope = listener[i][1];
fn.apply(scope, args);
}
};
/**
* Execute the native counterpart.
*
* @param [ String ] action The name of the action.
* @param [ Array ] args Array of arguments.
* @param [ Function] callback The callback function.
* @param [ Object ] scope The scope for the function.
*
* @return [ Void ]
*/
exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope),
params = [];
if (Array.isArray(args)) {
params = args;
} else if (args) {
params.push(args);
}
exec(fn, null, 'LocalNotification', action, params);
};
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered
// and all queued events can be executed.
exec(null, null, 'LocalNotification', 'deviceready', []);
});
// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
// Device plugin is ready now
channel.onCordovaInfoReady.subscribe(function () {
// Merge platform specifics into defaults
exports.applyPlatformSpecificOptions();
});
});
});
......@@ -40,40 +40,19 @@ exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope);
};
// /**
// * Returns the default settings.
// *
// * @return {Object}
// */
// exports.getDefaults = function () {
// return this.core.getDefaults();
// };
// /**
// * Overwrite default settings.
// *
// * @param {Object} defaults
// */
// exports.setDefaults = function (defaults) {
// this.core.setDefaults(defaults);
// };
// /**
// * Schedule a new local notification.
// *
// * @param {Object} notifications
// * The notification properties
// * @param {Function} callback
// * A function to be called after the notification has been canceled
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.schedule = function (notifications, callback, scope, args) {
// this.core.schedule(notifications, callback, scope, args);
// };
/**
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (notifications, callback, scope, args) {
this.core.schedule(notifications, callback, scope, args);
};
// /**
// * Update existing notifications specified by IDs in options.
......@@ -92,248 +71,255 @@ exports.requestPermission = function (callback, scope) {
// this.core.update(notifications, callback, scope, args);
// };
// /**
// * Clear the specified notification.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A function to be called after the notification has been cleared
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.clear = function (ids, callback, scope) {
// this.core.clear(ids, callback, scope);
// };
/**
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
this.core.clear(ids, callback, scope);
};
// /**
// * Clear all previously sheduled notifications.
// *
// * @param {Function} callback
// * A function to be called after all notifications have been cleared
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.clearAll = function (callback, scope) {
// this.core.clearAll(callback, scope);
// };
/**
* Clear all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.core.clearAll(callback, scope);
};
// /**
// * Cancel the specified notifications.
// *
// * @param {String[]} ids
// * The IDs of the notifications
// * @param {Function} callback
// * A function to be called after the notifications has been canceled
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.cancel = function (ids, callback, scope) {
// this.core.cancel(ids, callback, scope);
// };
/**
* Cancel the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
this.core.cancel(ids, callback, scope);
};
// /**
// * Remove all previously registered notifications.
// *
// * @param {Function} callback
// * A function to be called after all notifications have been canceled
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.cancelAll = function (callback, scope) {
// this.core.cancelAll(callback, scope);
// };
/**
* Cancel all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.core.cancelAll(callback, scope);
};
// /**
// * Check if a notification with an ID is present.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.isPresent = function (id, callback, scope) {
// this.core.isPresent(id, callback, scope);
// };
/**
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.core.isPresent(id, callback, scope);
};
// /**
// * Check if a notification with an ID is scheduled.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.isScheduled = function (id, callback, scope) {
// this.core.isScheduled(id, callback, scope);
// };
/**
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.core.isScheduled(id, callback, scope);
};
// *
// * Check if a notification with an ID was triggered.
// *
// * @param {String} id
// * The ID of the notification
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
/**
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.core.isTriggered(id, callback, scope);
};
// exports.isTriggered = function (id, callback, scope) {
// this.core.isTriggered(id, callback, scope);
// };
/**
* List of all notification ids.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.core.getAllIds(callback, scope);
};
// /**
// * List all local notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAllIds = function (callback, scope) {
// this.core.getAllIds(callback, scope);
// };
/**
* Alias for `getAllIds`.
*/
exports.getIds = function () {
this.getAllIds.apply(this, arguments);
};
// /**
// * Alias for `getAllIds`.
// */
// exports.getIds = function () {
// this.getAllIds.apply(this, arguments);
// };
/**
* List of all scheduled notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.core.getScheduledIds(callback, scope);
};
// /**
// * List all scheduled notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getScheduledIds = function (callback, scope) {
// this.core.getScheduledIds(callback, scope);
// };
/**
* List of all triggered notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.core.getTriggeredIds(callback, scope);
};
// /**
// * List all triggered notification IDs.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getTriggeredIds = function (callback, scope) {
// this.core.getTriggeredIds(callback, scope);
// };
/**
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function (ids, callback, scope) {
this.core.get(ids, callback, scope);
};
// /**
// * Property list for given local notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.get = function () {
// this.core.get.apply(this.core, arguments);
// };
/**
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.core.getAll(callback, scope);
};
// /**
// * Property list for all local notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAll = function (callback, scope) {
// this.core.getAll(callback, scope);
// };
/**
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled(ids, callback, scope);
};
// /**
// * Property list for given scheduled notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getScheduled = function () {
// this.core.getScheduled.apply(this.core, arguments);
// };
/**
* List of all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.core.getAllScheduled(callback, scope);
};
// /**
// * Property list for all scheduled notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAllScheduled = function (callback, scope) {
// this.core.getAllScheduled(callback, scope);
// };
/**
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered(ids, callback, scope);
};
// /**
// * Property list for given triggered notifications.
// * If called without IDs, all notification will be returned.
// *
// * @param {Number[]?} ids
// * Set of notification IDs
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getTriggered = function () {
// this.core.getTriggered.apply(this.core, arguments);
// };
/**
* List of all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.core.getAllTriggered(callback, scope);
};
// /**
// * Property list for all triggered notifications.
// *
// * @param {Function} callback
// * A callback function to be called with the list
// * @param {Object?} scope
// * The scope for the callback function
// */
// exports.getAllTriggered = function (callback, scope) {
// this.core.getAllTriggered(callback, scope);
// };
/**
* The (platform specific) default settings.
*
* @return [ Object ]
*/
exports.getDefaults = function () {
return this.core.getDefaults();
};
// /**
// * Register callback for given event.
// *
// * @param {String} event
// * The event's name
// * @param {Function} callback
// * The function to be exec as callback
// * @param {Object?} scope
// * The callback function's scope
// */
// exports.on = function (event, callback, scope) {
// this.core.on(event, callback, scope);
// };
/**
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.setDefaults = function (defaults) {
this.core.setDefaults(defaults);
};
// /**
// * Unregister callback for given event.
// *
// * @param {String} event
// * The event's name
// * @param {Function} callback
// * The function to be exec as callback
// */
// exports.un = function (event, callback) {
// this.core.un(event, callback);
// };
/**
* Register callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
this.core.on(event, callback, scope);
};
/**
* Unregister callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
this.core.un(event, callback);
};
});
......@@ -27,7 +27,6 @@
<!-- dependencies -->
<dependency id="cordova-plugin-device" />
<!-- <dependency id="cordova-plugin-app-event" /> -->
<!-- js -->
<js-module src="www/local-notification.js" name="LocalNotification">
......@@ -59,17 +58,17 @@
<header-file src="src/ios/APPLocalNotification.h" />
<source-file src="src/ios/APPLocalNotification.m" />
<!-- <header-file src="src/ios/APPLocalNotificationOptions.h" />
<source-file src="src/ios/APPLocalNotificationOptions.m" />
<header-file src="src/ios/APPNotificationContent.h" />
<source-file src="src/ios/APPNotificationContent.m" />
<header-file src="src/ios/APPNotificationOptions.h" />
<source-file src="src/ios/APPNotificationOptions.m" />
<header-file src="src/ios/UNUserNotificationCenter+APPLocalNotification.h" />
<source-file src="src/ios/UNUserNotificationCenter+APPLocalNotification.m" />
<header-file src="src/ios/UNMutableNotificationContent+APPLocalNotification.h" />
<source-file src="src/ios/UNMutableNotificationContent+APPLocalNotification.m" />
<header-file src="src/ios/UNNotificationRequest+APPLocalNotification.h" />
<source-file src="src/ios/UNNotificationRequest+APPLocalNotification.m" /> -->
<source-file src="src/ios/UNNotificationRequest+APPLocalNotification.m" />
</platform>
......
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
* Copyright (c) 2013 by appPlant GmbH. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
......@@ -21,7 +21,6 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@import UserNotifications;
......@@ -31,23 +30,23 @@
// Execute all queued events
- (void) deviceready:(CDVInvokedUrlCommand*)command;
// Inform if the app has the permission to show notifications
- (void) hasPermission:(CDVInvokedUrlCommand*)command;
// Register permission to show notifications
- (void) registerPermission:(CDVInvokedUrlCommand*)command;
// Check permission to show notifications
- (void) check:(CDVInvokedUrlCommand*)command;
// Request permission to show notifications
- (void) request:(CDVInvokedUrlCommand*)command;
// Schedule set of notifications
// Schedule notifications
- (void) schedule:(CDVInvokedUrlCommand*)command;
// Update set of notifications
- (void) update:(CDVInvokedUrlCommand*)command;
// Cancel set of notifications
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// Clear set of notifications
//// Update set of notifications
//- (void) update:(CDVInvokedUrlCommand*)command;
// Clear notifications by id
- (void) clear:(CDVInvokedUrlCommand*)command;
// Clear all notifications
- (void) clearAll:(CDVInvokedUrlCommand*)command;
// Cancel notifications by id
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is present
- (void) isPresent:(CDVInvokedUrlCommand*)command;
......@@ -56,25 +55,25 @@
// If a notification with an ID is triggered
- (void) isTriggered:(CDVInvokedUrlCommand*)command;
// List all ids from all local notifications
- (void) getAllIds:(CDVInvokedUrlCommand*)command;
// List all ids from all pending notifications
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command;
// List all ids from all triggered notifications
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command;
// List of all notification IDs
- (void) ids:(CDVInvokedUrlCommand*)command;
// List of all scheduled notification IDs
- (void) scheduledIds:(CDVInvokedUrlCommand*)command;
// List of all triggered notification IDs
- (void) triggeredIds:(CDVInvokedUrlCommand*)command;
// Propertys for given local notification
- (void) getSingle:(CDVInvokedUrlCommand*)command;
// Propertya for given scheduled notification
- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command;
// Propertys for given triggered notification
- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command;
// Notification by id
- (void) notification:(CDVInvokedUrlCommand*)command;
// Scheduled notification by id
- (void) scheduledNotification:(CDVInvokedUrlCommand*)command;
// Triggered notification by id
- (void) triggeredNotification:(CDVInvokedUrlCommand*)command;
// Property list for given local notifications
- (void) getAll:(CDVInvokedUrlCommand*)command;
// Property list for given scheduled notifications
- (void) getScheduled:(CDVInvokedUrlCommand*)command;
// Property list for given triggered notifications
- (void) getTriggered:(CDVInvokedUrlCommand*)command;
// List of notifications by id
- (void) notifications:(CDVInvokedUrlCommand*)command;
// List of scheduled notifications by id
- (void) scheduledNotifications:(CDVInvokedUrlCommand*)command;
// List of triggered notifications by id
- (void) triggeredNotifications:(CDVInvokedUrlCommand*)command;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
* Copyright (c) 2013 by appPlant GmbH. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
......@@ -22,31 +22,18 @@
*/
#import "APPLocalNotification.h"
#import "APPLocalNotificationOptions.h"
#import "APPNotificationOptions.h"
#import "UNUserNotificationCenter+APPLocalNotification.h"
#import "UNNotificationRequest+APPLocalNotification.h"
#import "UNMutableNotificationContent+APPLocalNotification.h"
#import "APPLocalNotificationOptions.ios9.h"
#import "UIApplication+APPLocalNotification.ios9.h"
#import "UILocalNotification+APPLocalNotification.ios9.h"
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#import "APPNotificationContent.h"
@interface APPLocalNotification ()
// Property reader for [self app]
@property (readonly, getter=app) UIApplication* app;
// Property reader for [self center]
@property (readonly, getter=center) UNUserNotificationCenter* center;
// All events will be queued until deviceready has been fired
@property (strong, nonatomic) UIApplication* app;
@property (strong, nonatomic) UNUserNotificationCenter* center;
@property (readwrite, assign) BOOL deviceready;
// Event queue
@property (readonly, nonatomic, retain) NSMutableArray* eventQueue;
// IOS9: TODO remove later
@property (nonatomic, retain) CDVInvokedUrlCommand* command;
@end
@implementation APPLocalNotification
......@@ -58,6 +45,8 @@
/**
* Execute all queued events.
*
* @return [ Void ]
*/
- (void) deviceready:(CDVInvokedUrlCommand*)command
{
......@@ -71,111 +60,95 @@
}
/**
* Schedule a set of notifications.
* Schedule notifications.
*
* @param [Array<Hash>] properties A list of key-value properties.
*
* @param properties
* A dict of properties for each notification
* @return [ Void ]
*/
- (void) schedule:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
for (NSDictionary* options in notifications) {
UNMutableNotificationContent* notification;
APPNotificationContent* notification;
notification = [[UNMutableNotificationContent alloc]
notification = [[APPNotificationContent alloc]
initWithOptions:options];
[self scheduleNotification:notification];
//[self fireEvent:@"add" notification:notification];
}
} else {
for (NSDictionary* options in notifications) {
UILocalNotification* notification;
notification = [[UILocalNotification alloc]
initWithOptions:options];
[self scheduleLocalNotification:[notification copy]];
[self fireEvent:@"schedule" localnotification:notification];
if (notifications.count > 1) {
[NSThread sleepForTimeInterval:0.01];
}
}
}
[self execCallback:command];
}];
}
/**
* Update a set of notifications.
*
* @param properties
* A dict of properties for each notification
*/
- (void) update:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
for (NSDictionary* options in notifications) {
NSNumber* id = [options objectForKey:@"id"];
UNNotificationRequest* notification;
notification = [self.center getNotificationWithId:id];
if (!notification)
continue;
// [self updateNotification:[notification copy]
// withOptions:options];
//
// [self fireEvent:@"update" notification:notification];
//
// if (notifications.count > 1) {
// [NSThread sleepForTimeInterval:0.01];
// }
}
} else {
for (NSDictionary* options in notifications) {
NSNumber* id = [options objectForKey:@"id"];
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self updateLocalNotification:[notification copy]
withOptions:options];
[self fireEvent:@"update" localnotification:notification];
if (notifications.count > 1) {
[NSThread sleepForTimeInterval:0.01];
}
}
}
[self execCallback:command];
}];
}
///**
// * Update a set of notifications.
// *
// * @param properties
// * A dict of properties for each notification
// */
//- (void) update:(CDVInvokedUrlCommand*)command
//{
// NSArray* notifications = command.arguments;
//
// [self.commandDelegate runInBackground:^{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
// for (NSDictionary* options in notifications) {
// NSNumber* id = [options objectForKey:@"id"];
// UNNotificationRequest* notification;
//
// notification = [self.center getNotificationWithId:id];
//
// if (!notification)
// continue;
//
// // [self updateNotification:[notification copy]
// // withOptions:options];
// //
// // [self fireEvent:@"update" notification:notification];
// //
// // if (notifications.count > 1) {
// // [NSThread sleepForTimeInterval:0.01];
// // }
// }
// } else {
// for (NSDictionary* options in notifications) {
// NSNumber* id = [options objectForKey:@"id"];
// UILocalNotification* notification;
//
// notification = [self.app localNotificationWithId:id];
//
// if (!notification)
// continue;
//
// [self updateLocalNotification:[notification copy]
// withOptions:options];
//
// [self fireEvent:@"update" localnotification:notification];
//
// if (notifications.count > 1) {
// [NSThread sleepForTimeInterval:0.01];
// }
// }
// }
//
// [self execCallback:command];
// }];
//}
/**
* Cancel a set of notifications.
* Clear notifications by id.
*
* @param [ Array<Int> ] The IDs of the notifications to clear.
*
* @param ids
* The IDs of the notifications
* @return [ Void ]
*/
- (void) cancel:(CDVInvokedUrlCommand*)command
- (void) clear:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
for (NSNumber* id in command.arguments) {
UNNotificationRequest* notification;
......@@ -184,21 +157,8 @@
if (!notification)
continue;
[self.center cancelNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
} else {
for (NSNumber* id in command.arguments) {
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" localnotification:notification];
}
[self.center clearNotification:notification];
[self fireEvent:@"clear" notification:notification];
}
[self execCallback:command];
......@@ -206,27 +166,30 @@
}
/**
* Cancel all local notifications.
* Clear all local notifications.
*
* @return [ Void ]
*/
- (void) cancelAll:(CDVInvokedUrlCommand*)command
- (void) clearAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self cancelAllNotifications];
[self fireEvent:@"cancelall"];
[self.center clearAllNotifications];
[self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"clearall"];
[self execCallback:command];
}];
}
/**
* Clear a set of notifications.
* Cancel notifications by id.
*
* @param [ Array<Int> ] The IDs of the notifications to clear.
*
* @param ids
* The IDs of the notifications
* @return [ Void ]
*/
- (void) clear:(CDVInvokedUrlCommand*)command
- (void) cancel:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
for (NSNumber* id in command.arguments) {
UNNotificationRequest* notification;
......@@ -235,21 +198,8 @@
if (!notification)
continue;
[self.center clearNotification:notification];
[self fireEvent:@"clear" notification:notification];
}
} else {
for (NSNumber* id in command.arguments) {
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self.app clearLocalNotification:notification];
[self fireEvent:@"clear" localnotification:notification];
}
[self.center cancelNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
[self execCallback:command];
......@@ -257,13 +207,16 @@
}
/**
* Clear all local notifications.
* Cancel all local notifications.
*
* @return [ Void ]
*/
- (void) clearAll:(CDVInvokedUrlCommand*)command
- (void) cancelAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self clearAllNotifications];
[self fireEvent:@"clearall"];
[self.center cancelAllNotifications];
[self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"cancelall"];
[self execCallback:command];
}];
}
......@@ -271,58 +224,52 @@
/**
* If a notification by ID is present.
*
* @param id
* The ID of the notification
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isPresent:(CDVInvokedUrlCommand *)command
{
[self isPresent:command type:NotifcationTypeAll];
[self exist:command byType:NotifcationTypeAll];
}
/**
* If a notification by ID is scheduled.
*
* @param id
* The ID of the notification
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isScheduled:(CDVInvokedUrlCommand*)command
{
[self isPresent:command type:NotifcationTypeScheduled];
[self exist:command byType:NotifcationTypeScheduled];
}
/**
* Check if a notification with an ID is triggered.
*
* @param id
* The ID of the notification
* @param [ Number ]id The ID of the notification.
*
* @return [ Void ]
*/
- (void) isTriggered:(CDVInvokedUrlCommand*)command
{
[self isPresent:command type:NotifcationTypeTriggered];
[self exist:command byType:NotifcationTypeTriggered];
}
/**
* Check if a notification with an ID exists.
* Check if a notification exists by ID and type.
*
* @param type
* The notification life cycle type
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) isPresent:(CDVInvokedUrlCommand*)command
type:(APPNotificationType)type;
- (void) exist:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSNumber* id = [command argumentAtIndex:0];
BOOL exist;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
exist = [self.center notificationExist:id type:type];
} else {
if (type == NotifcationTypeAll) {
exist = [self.app localNotificationExist:id];
} else {
exist = [self.app localNotificationExist:id type:type];
}
}
BOOL exist = [_center notificationExist:id type:type];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
......@@ -334,52 +281,47 @@
}
/**
* List all ids from all local notifications.
* List of all notification IDs.
*
* @return [ Void ]
*/
- (void) getAllIds:(CDVInvokedUrlCommand*)command
- (void) ids:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeAll];
[self ids:command byType:NotifcationTypeAll];
}
/**
* List all ids from all pending notifications.
* List of all scheduled notification IDs.
*
* @return [ Void ]
*/
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command
- (void) scheduledIds:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeScheduled];
[self ids:command byType:NotifcationTypeScheduled];
}
/**
* List all ids from all triggered notifications.
* List of all triggered notification IDs.
*
* @return [ Void ]
*/
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command
- (void) triggeredIds:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeTriggered];
[self ids:command byType:NotifcationTypeTriggered];
}
/**
* List of ids for given local notifications.
*
* @param type
* Notification life cycle type
* @param ids
* The IDs of the notifications
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) getIds:(CDVInvokedUrlCommand*)command
- (void) ids:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
ids = [self.center getNotificationIdsByType:type];
} else {
if (type == NotifcationTypeAll) {
ids = [self.app localNotificationIds];
} else {
ids = [self.app localNotificationIdsByType:type];
}
}
NSArray* ids = [self.center getNotificationIdsByType:type];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
......@@ -391,141 +333,129 @@
}
/**
* Propertys for given local notification.
* Notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) getSingle:(CDVInvokedUrlCommand*)command
- (void) notification:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeAll];
[self notification:command byType:NotifcationTypeAll];
}
/**
* Propertya for given scheduled notification.
* Scheduled notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command
- (void) scheduledNotification:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeScheduled];
[self notification:command byType:NotifcationTypeScheduled];
}
// Propertys for given triggered notification
- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command
/**
* Triggered notification by id.
*
* @param [ Number ] id The id of the notification to return.
*
* @return [ Void ]
*/
- (void) triggeredNotification:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeTriggered];
[self notification:command byType:NotifcationTypeTriggered];
}
/**
* Property list for given local notifications.
* Notification by type and id.
*
* @param ids
* The IDs of the notifications
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @return [ Void ]
*/
- (void) getAll:(CDVInvokedUrlCommand*)command
- (void) notification:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self getOptions:command byType:NotifcationTypeAll];
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
notifications = [_center getNotificationOptionsByType:type andId:ids];
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:[notifications firstObject]];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Property list for given scheduled notifications.
* List of notifications by id.
*
* @param ids
* The IDs of the notifications
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @return [ Void ]
*/
- (void) getScheduled:(CDVInvokedUrlCommand*)command
- (void) notifications:(CDVInvokedUrlCommand*)command
{
[self getOptions:command byType:NotifcationTypeScheduled];
[self notifications:command byType:NotifcationTypeAll];
}
/**
* Property list for given triggered notifications.
* List of scheduled notifications by id.
*
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @param ids
* The IDs of the notifications
* @return [ Void ]
*/
- (void) getTriggered:(CDVInvokedUrlCommand *)command
- (void) scheduledNotifications:(CDVInvokedUrlCommand*)command
{
[self getOptions:command byType:NotifcationTypeTriggered];
[self notifications:command byType:NotifcationTypeScheduled];
}
/**
* Propertys for given triggered notification.
* List of triggered notifications by id.
*
* @param [ Array<Number> ] ids The ids of the notifications to return.
*
* @param type
* Notification life cycle type
* @param ids
* The ID of the notification
* @return [ Void ]
*/
- (void) getOption:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
- (void) triggeredNotifications:(CDVInvokedUrlCommand *)command
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
notifications = [self.center getNotificationOptionsByType:type
andId:ids];
} else {
if (type == NotifcationTypeAll) {
notifications = [self.app localNotificationOptionsById:ids];
}
else {
notifications = [self.app localNotificationOptionsByType:type
andId:ids];
}
}
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:[notifications firstObject]];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
[self notifications:command byType:NotifcationTypeTriggered];
}
/**
* Property list for given triggered notifications.
* List of notifications by type and id.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
*
* @param type
* Notification life cycle type
* @param ids
* The IDs of the notifications
* @return [ Void ]
*/
- (void) getOptions:(CDVInvokedUrlCommand*)command
- (void) notifications:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
if (type == NotifcationTypeAll && ids.count == 0) {
notifications = [self.center getNotificationOptions];
}
else if (type == NotifcationTypeAll) {
notifications = [self.center getNotificationOptionsById:ids];
}
else if (ids.count == 0) {
notifications = [self.center getNotificationOptionsByType:type];
}
else {
notifications = [self.center getNotificationOptionsByType:type
andId:ids];
}
} else {
if (type == NotifcationTypeAll && ids.count == 0) {
notifications = [self.app localNotificationOptions];
notifications = [_center getNotificationOptions];
}
else if (type == NotifcationTypeAll) {
notifications = [self.app localNotificationOptionsById:ids];
notifications = [_center getNotificationOptionsById:ids];
}
else if (ids.count == 0) {
notifications = [self.app localNotificationOptionsByType:type];
notifications = [_center getNotificationOptionsByType:type];
}
else {
notifications = [self.app localNotificationOptionsByType:type
notifications = [_center getNotificationOptionsByType:type
andId:ids];
}
}
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
......@@ -537,145 +467,89 @@
}
/**
* Inform if the app has the permission to show
* badges and local notifications.
* Check for permission to show notifications.
*
* @return [ Void ]
*/
- (void) hasPermission:(CDVInvokedUrlCommand*)command
- (void) check:(CDVInvokedUrlCommand*)command
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
[self.commandDelegate runInBackground:^{
[self.center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
[_center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized;
BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled;
BOOL permitted = authorized && enabled;
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:permitted];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}];
} else {
[self.commandDelegate runInBackground:^{
CDVPluginResult* result;
BOOL hasPermission;
hasPermission = [self.app hasPermissionToScheduleLocalNotifications];
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:hasPermission];
messageAsBool:permitted];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
}
/**
* Ask for permission to show badges.
* Request for permission to show notifcations.
*
* @return [ Void ]
*/
- (void) registerPermission:(CDVInvokedUrlCommand*)command
- (void) request:(CDVInvokedUrlCommand*)command
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
[self.commandDelegate runInBackground:^{
UNAuthorizationOptions options =
(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
[self.center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError* e) {
[self hasPermission:command];
}];
[self check:command];
}];
} else {
if ([[UIApplication sharedApplication]
respondsToSelector:@selector(registerUserNotificationSettings:)])
{
_command = command;
[self.commandDelegate runInBackground:^{
[self.app registerPermissionToScheduleLocalNotifications];
}];
} else {
[self hasPermission:command];
}
}
}
#pragma mark -
#pragma mark Core Logic
#pragma mark Private
/**
* Schedule the local notification.
*/
- (void) scheduleNotification:(UNMutableNotificationContent*)notification
- (void) scheduleNotification:(APPNotificationContent*)notification
{
[self.center addNotificationRequest:notification.request
withCompletionHandler:^(NSError* e) {
[self fireEvent:@"add" notification:notification.request];
__weak APPLocalNotification* weakSelf = self;
UNNotificationRequest* request = notification.request;
[_center addNotificationRequest:request withCompletionHandler:^(NSError* e) {
__strong APPLocalNotification* strongSelf = weakSelf;
[strongSelf fireEvent:@"add" notification:request];
}];
}
/**
* Update the local notification.
*/
- (void) updateNotification:(UILocalNotification*)notification
withOptions:(NSDictionary*)newOptions
{
NSMutableDictionary* options = [notification.userInfo mutableCopy];
[options addEntriesFromDictionary:newOptions];
[options setObject:[NSDate date] forKey:@"updatedAt"];
// notification = [[UILocalNotification alloc]
// initWithOptions:options];
///**
// * Update the local notification.
// */
//- (void) updateNotification:(UILocalNotification*)notification
// withOptions:(NSDictionary*)newOptions
//{APPNotificationRequest*
// NSMutableDictionary* options = [notification.userInfo mutableCopy];
//
// [self scheduleLocalNotification:notification];
}
/**
* Cancel all local notifications.
*/
- (void) cancelAllNotifications
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
[self.center cancelAllNotifications];
} else {
[self.app cancelAllLocalNotifications];
}
[self.app setApplicationIconBadgeNumber:0];
}
/**
* Clear all local notifications.
*/
- (void) clearAllNotifications
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
[self.center clearAllNotifications];
} else {
[self.app clearAllLocalNotifications];
}
[self.app setApplicationIconBadgeNumber:0];
}
// [options addEntriesFromDictionary:newOptions];
// [options setObject:[NSDate date] forKey:@"updatedAt"];
//
//// notification = [[UILocalNotification alloc]
//// initWithOptions:options];
////
//// [self scheduleLocalNotification:notification];
//}
#pragma mark -
#pragma mark Delegates
#pragma mark UNUserNotificationCenterDelegate
/**
* Called when a notification is delivered to a foreground app.
* Called when a notification is delivered to the app while being in foreground.
*/
- (void) userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
[self fireEvent:@"trigger" notification:notification.request];
completionHandler(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
/**
* Called to let your app know which action was selected by the user for a given
* notification.
......@@ -685,17 +559,18 @@
withCompletionHandler:(void (^)())completionHandler
{
UNNotificationRequest* notification = response.notification.request;
NSString* action = response.actionIdentifier;
NSString* event = action;
[self fireEvent:@"click" notification:notification];
if ([notification.options isRepeating]) {
[self.center clearNotification:notification];
[self fireEvent:@"clear" notification:notification];
} else {
[self.center cancelNotification:notification];
[self fireEvent:@"cancel" notification:notification];
if ([action isEqualToString:UNNotificationDefaultActionIdentifier]) {
event = @"click";
} else
if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
event = @"clear";
}
[self fireEvent:event notification:notification];
completionHandler();
}
......@@ -708,22 +583,24 @@
- (void) pluginInitialize
{
eventQueue = [[NSMutableArray alloc] init];
_app = [UIApplication sharedApplication];
_center = [UNUserNotificationCenter currentNotificationCenter];
self.center.delegate = self;
_center.delegate = self;
[_center registerGeneralNotificationCategory];
}
#pragma mark -
#pragma mark Helper
/**
* Retrieves the application state
* Retrieve the state of the application.
*
* @return
* Either "background" or "foreground"
* @return "background" or "foreground"
*/
- (NSString*) applicationState
{
UIApplicationState state = [self.app applicationState];
UIApplicationState state = [_app applicationState];
bool isActive = state == UIApplicationStateActive;
......@@ -743,23 +620,11 @@
}
/**
* Short hand for shared application instance.
*/
- (UIApplication*) app
{
return [UIApplication sharedApplication];
}
/**
* Short hand for current notification center.
*/
- (UNUserNotificationCenter*) center
{
return [UNUserNotificationCenter currentNotificationCenter];
}
/**
* Fire general event.
*
* @param [ NSString* ] event The name of the event to fire.
*
* @return [ Void ]
*/
- (void) fireEvent:(NSString*)event
{
......@@ -767,17 +632,22 @@
}
/**
* Fire event for local notification.
* Fire event for about a local notification.
*
* @param [ NSString* ] event The name of the event to fire.
* @param [ APPNotificationRequest* ] notification The local notification.
*
* @return [ Void ]
*/
- (void) fireEvent:(NSString*)event
notification:(UNNotificationRequest*)notification
notification:(UNNotificationRequest*)request
{
NSString* js;
NSString* appState = [self applicationState];
NSString* params = [NSString stringWithFormat:@"\"%@\"", appState];
if (notification) {
NSString* args = [notification encodeToJSON];
if (request) {
NSString* args = [request encodeToJSON];
params = [NSString stringWithFormat:@"%@,'%@'", args, appState];
}
......@@ -792,165 +662,4 @@
}
}
#pragma mark -
#pragma mark ios 9
/**
* Schedule the local notification.
*/
- (void) scheduleLocalNotification:(UILocalNotification*)notification
{
[self cancelForerunnerLocalNotification:notification];
[self.app scheduleLocalNotification:notification];
}
/**
* Update the local notification.
*/
- (void) updateLocalNotification:(UILocalNotification*)notification
withOptions:(NSDictionary*)newOptions
{
NSMutableDictionary* options = [notification.userInfo mutableCopy];
[options addEntriesFromDictionary:newOptions];
[options setObject:[NSDate date] forKey:@"updatedAt"];
notification = [[UILocalNotification alloc]
initWithOptions:options];
[self scheduleLocalNotification:notification];
}
/**
* Cancel a maybe given forerunner with the same ID.
*/
- (void) cancelForerunnerLocalNotification:(UILocalNotification*)notification
{
NSNumber* id = notification.options.id;
UILocalNotification* forerunner;
forerunner = [self.app localNotificationWithId:id];
if (!forerunner)
return;
[self.app cancelLocalNotification:forerunner];
}
/**
* Cancels all non-repeating local notification older then
* a specific amount of seconds
*/
- (void) cancelAllNotificationsWhichAreOlderThen:(float)seconds
{
NSArray* notifications;
notifications = [self.app localNotifications];
for (UILocalNotification* notification in notifications)
{
if (![notification isRepeating]
&& notification.timeIntervalSinceFireDate > seconds)
{
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" localnotification:notification];
}
}
}
/**
* Calls the cancel or trigger event after a local notification was received.
* Cancels the local notification if autoCancel was set to true.
*/
- (void) didReceiveLocalNotification:(NSNotification*)localNotification
{
UILocalNotification* notification = [localNotification object];
if ([notification userInfo] == NULL || [notification wasUpdated])
return;
NSTimeInterval timeInterval = [notification timeIntervalSinceLastTrigger];
NSString* event = timeInterval < 0.2 && deviceready ? @"trigger" : @"click";
[self fireEvent:event localnotification:notification];
if (![event isEqualToString:@"click"])
return;
if ([notification isRepeating]) {
[self fireEvent:@"clear" localnotification:notification];
} else {
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" localnotification:notification];
}
}
/**
* Called when app has started
* (by clicking on a local notification).
*/
- (void) didFinishLaunchingWithOptions:(NSNotification*)notification
{
NSDictionary* launchOptions = [notification userInfo];
UILocalNotification* localNotification;
localNotification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
[self didReceiveLocalNotification:
[NSNotification notificationWithName:CDVLocalNotification
object:localNotification]];
}
}
/**
* Called on notification settings registration is completed.
*/
- (void) didRegisterUserNotificationSettings:(UIUserNotificationSettings*)settings
{
if (_command) {
[self hasPermission:_command];
_command = NULL;
}
}
/**
* Cancels all single non-repeating notifications which are older then 5 days
* before the app terminates.
*/
- (void) onAppTerminate
{
[self cancelAllNotificationsWhichAreOlderThen:432000];
}
/**
* Fire event for local notification.
*/
- (void) fireEvent:(NSString*)event localnotification:(UILocalNotification*)notification
{
NSString* js;
NSString* params = [NSString stringWithFormat:
@"\"%@\"", self.applicationState];
if (notification) {
NSString* args = [notification encodeToJSON];
params = [NSString stringWithFormat:
@"%@,'%@'",
args, self.applicationState];
}
js = [NSString stringWithFormat:
@"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
event, params];
if (deviceready) {
[self.commandDelegate evalJs:js];
} else {
[self.eventQueue addObject:js];
}
}
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotificationOptions.h"
@import UserNotifications;
@interface APPLocalNotificationOptions ()
// The dictionary which contains all notification properties
@property(nonatomic, retain) NSDictionary* dict;
@end
@implementation APPLocalNotificationOptions
@synthesize dict;
#pragma mark -
#pragma mark Initialization
/**
* Initialize the object with the given options when calling on JS side:
* notification.local.add(options)
*/
- (id) initWithDict:(NSDictionary*)dictionary
{
self = [self init];
self.dict = dictionary;
return self;
}
#pragma mark -
#pragma mark Attributes
/**
* The notification's ID.
*/
- (NSNumber*) id
{
NSInteger id = [[dict objectForKey:@"id"] integerValue];
return [NSNumber numberWithInteger:id];
}
/**
* The notification's ID as a string.
*/
- (NSString*) identifier
{
return [NSString stringWithFormat:@"%@", self.id];
}
/**
* The notification's title.
*/
- (NSString*) title
{
return [dict objectForKey:@"title"];
}
/**
* The notification's title.
*/
- (NSString*) subtitle
{
NSArray *parts = [self.title componentsSeparatedByString:@"\n"];
return parts.count < 2 ? @"" : [parts objectAtIndex:1];
}
/**
* The notification's message.
*/
- (NSString*) text
{
return [dict objectForKey:@"text"];
}
/**
* The notification's badge number.
*/
- (NSNumber*) badge
{
return [NSNumber numberWithInt:[[dict objectForKey:@"badge"] intValue]];
}
/**
* The notification's sound path.
*/
- (UNNotificationSound*) sound
{
NSString* path = [dict objectForKey:@"sound"];
NSString* file;
if ([self stringIsNullOrEmpty:path])
return NULL;
if ([path isEqualToString:@"res://platform_default"])
return [UNNotificationSound defaultSound];
if ([path hasPrefix:@"file:/"]) {
file = [self soundNameForAsset:path];
} else
if ([path hasPrefix:@"res:"]) {
file = [self soundNameForResource:path];
}
return [UNNotificationSound soundNamed:file];
}
/**
* The notification's fire date.
*/
- (NSDate*) fireDate
{
double timestamp = [[dict objectForKey:@"at"]
doubleValue];
return [NSDate dateWithTimeIntervalSince1970:timestamp];
}
/**
* If it's a repeating notification.
*/
- (BOOL) isRepeating
{
NSString* interval = [dict objectForKey:@"every"];
return ![self stringIsNullOrEmpty:interval];
}
#pragma mark -
#pragma mark Methods
/**
* Specify how and when to trigger the notification.
*/
- (UNNotificationTrigger*) trigger
{
return [self isRepeating] ? [self triggerWithDateMatchingComponents] : [self triggerWithTimeInterval];
}
/**
* The notification's user info dict.
*/
- (NSDictionary*) userInfo
{
if ([dict objectForKey:@"updatedAt"]) {
NSMutableDictionary* data = [dict mutableCopy];
[data removeObjectForKey:@"updatedAt"];
return data;
}
return dict;
}
#pragma mark -
#pragma mark Private
/**
* Returns a trigger based on a custom time interval in seconds.
*/
- (UNTimeIntervalNotificationTrigger*) triggerWithTimeInterval
{
return [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:[self timeInterval] repeats:NO];
}
/**
* Returns a trigger based on a calendar time.
*/
- (UNCalendarNotificationTrigger*) triggerWithDateMatchingComponents
{
NSCalendar* cal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *date = [cal components:[self repeatInterval]
fromDate:[self fireDate]];
[date setTimeZone:[NSTimeZone defaultTimeZone]];
return [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:YES];
}
/**
* Timeinterval between future fire date and now.
*/
- (double) timeInterval
{
return MAX(0.01f, [self.fireDate timeIntervalSinceDate:[NSDate date]]);
}
/**
* The notification's repeat interval.
*/
- (NSCalendarUnit) repeatInterval
{
NSString* interval = [dict objectForKey:@"every"];
NSCalendarUnit unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([self stringIsNullOrEmpty:interval]) {
return unitFlags;
}
else if ([interval isEqualToString:@"second"]) {
return NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay;
}
else if ([interval isEqualToString:@"minute"]) {
return NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitSecond;
}
else if ([interval isEqualToString:@"hour"]) {
return NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitMinute;
}
else if ([interval isEqualToString:@"day"]) {
return NSCalendarUnitHour|NSCalendarUnitMinute;
}
else if ([interval isEqualToString:@"week"]) {
return NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute;
}
else if ([interval isEqualToString:@"month"]) {
return NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute;
}
else if ([interval isEqualToString:@"year"]) {
return NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute;
}
return unitFlags;
}
/**
* Convert relative path to valid sound name attribute.
*/
- (NSString*) soundNameForAsset:(NSString*)path
{
return [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"www"];
}
/**
* Convert resource path to valid sound name attribute.
*/
- (NSString*) soundNameForResource:(NSString*)path
{
return [path pathComponents].lastObject;
}
/**
* If the string is empty.
*/
- (BOOL) stringIsNullOrEmpty:(NSString*)str
{
return (!str.length);
}
@end
......@@ -21,22 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "APPNotificationOptions.h"
@interface APPLocalNotificationOptions9 : NSObject
@import UserNotifications;
- (id) initWithDict:(NSDictionary*)dict;
@interface APPNotificationContent : UNMutableNotificationContent
@property (readonly, getter=id) NSNumber* id;
@property (readonly, getter=badgeNumber) NSInteger badgeNumber;
@property (readonly, getter=alertBody) NSString* alertBody;
@property (readonly, getter=soundName) NSString* soundName;
@property (readonly, getter=fireDate) NSDate* fireDate;
@property (readonly, getter=repeatInterval) NSCalendarUnit repeatInterval;
@property (readonly, getter=userInfo) NSDictionary* userInfo;
// If it's a repeating notification
- (BOOL) isRepeating;
- (id) initWithOptions:(NSDictionary*)dict;
- (APPNotificationOptions*) options;
- (UNNotificationRequest*) request;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationContent.h"
#import "APPNotificationOptions.h"
#import "UNUserNotificationCenter+APPLocalNotification.h"
#import <objc/runtime.h>
@import UserNotifications;
static char optionsKey;
@implementation APPNotificationContent : UNMutableNotificationContent
#pragma mark -
#pragma mark Init
/**
* Initialize a notification with the given options.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ UNMutableNotificationContent ]
*/
- (id) initWithOptions:(NSDictionary*)dict
{
self = [self init];
[self setUserInfo:dict];
[self __init];
return self;
}
/**
* Initialize a notification by using the options found under userInfo.
*
* @return [ Void ]
*/
- (void) __init
{
APPNotificationOptions* options = self.options;
self.title = options.title;
self.subtitle = options.subtitle;
self.body = options.text;
self.sound = options.sound;
self.badge = options.badge;
self.attachments = options.attachments;
self.categoryIdentifier = kAPPGeneralCategory;
}
#pragma mark -
#pragma mark Public
/**
* The options used to initialize the notification.
*
* @return [ APPNotificationOptions* ] options
*/
- (APPNotificationOptions*) options
{
APPNotificationOptions* options = [self getOptions];
if (!options) {
options = [[APPNotificationOptions alloc]
initWithDict:[self userInfo]];
[self setOptions:options];
}
return options;
}
/**
* The notifcations request ready to add to the notification center including
* all informations about trigger behavior.
*
* @return [ UNNotificationRequest* ]
*/
- (UNNotificationRequest*) request
{
APPNotificationOptions* opts = [self getOptions];
return [UNNotificationRequest requestWithIdentifier:opts.identifier
content:self
trigger:opts.trigger];
}
#pragma mark -
#pragma mark Private
/**
* The options used to initialize the notification.
*
* @return [ APPNotificationOptions* ]
*/
- (APPNotificationOptions*) getOptions
{
return objc_getAssociatedObject(self, &optionsKey);
}
/**
* Set the options used to initialize the notification.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ Void ]
*/
- (void) setOptions:(APPNotificationOptions*)options
{
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
......@@ -21,39 +21,21 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotificationOptions.ios9.h"
@import UserNotifications;
#ifndef APPNotificationType_DEFINED
typedef NS_ENUM(NSUInteger, APPNotificationType) {
NotifcationTypeAll = 0,
NotifcationTypeScheduled = 1,
NotifcationTypeTriggered = 2
};
#endif
@interface APPNotificationOptions : NSObject
@interface UILocalNotification (APPLocalNotification)
@property (readonly, getter=id) NSNumber* id;
@property (readonly, getter=identifier) NSString* identifier;
@property (readonly, getter=title) NSString* title;
@property (readonly, getter=subtitle) NSString* subtitle;
@property (readonly, getter=badge) NSNumber* badge;
@property (readonly, getter=text) NSString* text;
@property (readonly, getter=sound) UNNotificationSound* sound;
@property (readonly, getter=attachments) NSArray<UNNotificationAttachment *> * attachments;
@property (readonly, getter=userInfo) NSDictionary* userInfo;
// Initialize a new local notification
- (id) initWithOptions:(NSDictionary*)dict;
// The options provided by the plug-in
- (APPLocalNotificationOptions9*) options;
// Timeinterval since last trigger date
- (double) timeIntervalSinceLastTrigger;
// Timeinterval since fire date
- (double) timeIntervalSinceFireDate;
// If the fire date was in the past
- (BOOL) wasInThePast;
// If the notification was already scheduled
- (BOOL) isScheduled;
// If the notification was already triggered
- (BOOL) isTriggered;
// If the notification was updated
- (BOOL) wasUpdated;
// If it's a repeating notification
- (BOOL) isRepeating;
// Notifciation type
- (APPNotificationType) type;
// Encode the user info dict to JSON
- (NSString*) encodeToJSON;
- (id) initWithDict:(NSDictionary*)dict;
- (UNNotificationTrigger*) trigger;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationOptions.h"
@import UserNotifications;
@interface APPNotificationOptions ()
// The dictionary which contains all notification properties
@property(nonatomic, retain) NSDictionary* dict;
@end
@implementation APPNotificationOptions : NSObject
@synthesize dict;
#pragma mark -
#pragma mark Initialization
/**
* Initialize by using the given property values.
*
* @param [ NSDictionary* ] dict A key-value property map.
*
* @return [ APPNotificationOptions ]
*/
- (id) initWithDict:(NSDictionary*)dictionary
{
self = [self init];
self.dict = dictionary;
return self;
}
#pragma mark -
#pragma mark Properties
/**
* The ID for the notification.
*
* @return [ NSNumber* ]
*/
- (NSNumber*) id
{
NSInteger id = [[dict objectForKey:@"id"] integerValue];
return [NSNumber numberWithInteger:id];
}
/**
* The ID for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) identifier
{
return [NSString stringWithFormat:@"%@", self.id];
}
/**
* The title for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) title
{
return [dict objectForKey:@"title"];
}
/**
* The subtitle for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) subtitle
{
NSArray *parts = [self.title componentsSeparatedByString:@"\n"];
return parts.count < 2 ? @"" : [parts objectAtIndex:1];
}
/**
* The text for the notification.
*
* @return [ NSString* ]
*/
- (NSString*) text
{
return [dict objectForKey:@"text"];
}
/**
* The badge number for the notification.
*
* @return [ NSNumber* ]
*/
- (NSNumber*) badge
{
return [NSNumber numberWithInt:[[dict objectForKey:@"badge"] intValue]];
}
/**
* The sound file for the notification.
*
* @return [ UNNotificationSound* ]
*/
- (UNNotificationSound*) sound
{
NSString* path = [dict objectForKey:@"sound"];
NSString* file;
if (!path.length)
return NULL;
if ([path isEqualToString:@"res://platform_default"])
return [UNNotificationSound defaultSound];
if ([path hasPrefix:@"file:/"]) {
file = [self soundNameForAsset:path];
} else
if ([path hasPrefix:@"res:"]) {
file = [self soundNameForResource:path];
}
return [UNNotificationSound soundNamed:file];
}
/**
* The date when to fire the notification.
*
* @return [ NSDate* ]
*/
- (NSDate*) fireDate
{
double timestamp = [[dict objectForKey:@"at"]
doubleValue];
return [NSDate dateWithTimeIntervalSince1970:timestamp];
}
- (NSArray<UNNotificationAttachment *> *) attachments
{
NSArray* paths = [dict objectForKey:@"attachments"];
NSMutableArray* attachments = [[NSMutableArray alloc] init];
if (!paths)
return attachments;
for (NSString* path in paths) {
NSURL* url = [self urlForAttachmentPath:path];
UNNotificationAttachment* attachment;
attachment = [UNNotificationAttachment attachmentWithIdentifier:path
URL:url
options:NULL
error:NULL];
if (attachment) {
[attachments addObject:attachment];
}
}
return attachments;
}
#pragma mark -
#pragma mark Public
/**
* Specify how and when to trigger the notification.
*
* @return [ UNNotificationTrigger* ]
*/
- (UNNotificationTrigger*) trigger
{
if ([self isRepeating])
return [self repeatingTrigger];
return [self nonRepeatingTrigger];
}
/**
* The notification's user info dict.
*
* @return [ NSDictionary* ]
*/
- (NSDictionary*) userInfo
{
if ([dict objectForKey:@"updatedAt"]) {
NSMutableDictionary* data = [dict mutableCopy];
[data removeObjectForKey:@"updatedAt"];
return data;
}
return dict;
}
#pragma mark -
#pragma mark Private
/**
* If the notification shall be repeating.
*
* @return [ BOOL ]
*/
- (BOOL) isRepeating
{
id every = [dict objectForKey:@"every"];
if ([every isKindOfClass:NSString.class])
return ((NSString*) every).length > 0;
if ([every isKindOfClass:NSDictionary.class])
return ((NSDictionary*) every).count > 0;
return every > 0;
}
/**
* Non repeating trigger.
*
* @return [ UNTimeIntervalNotificationTrigger* ]
*/
- (UNTimeIntervalNotificationTrigger*) nonRepeatingTrigger
{
return [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:[self timeInterval] repeats:NO];
}
/**
* Repeating trigger.
*
* @return [ UNNotificationTrigger* ]
*/
- (UNNotificationTrigger*) repeatingTrigger
{
id every = [dict objectForKey:@"every"];
if ([every isKindOfClass:NSString.class])
return [self repeatingTriggerWithDateMatchingComponents];
if ([every isKindOfClass:NSDictionary.class])
return [self repeatingTriggerWithCustomDateMatchingComponents];
return [self repeatingTriggerWithTimeInterval];
}
/**
* A trigger based on a calendar time defined by the user.
*
* @return [ UNTimeIntervalNotificationTrigger* ]
*/
- (UNTimeIntervalNotificationTrigger*) repeatingTriggerWithTimeInterval
{
long interval = [[dict objectForKey:@"every"] longValue];
if (interval < 60) {
NSLog(@"time interval must be at least 60 if repeating");
interval = 60;
}
return [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:interval repeats:YES];
}
/**
* A repeating trigger based on a calendar time intervals defined by the plugin.
*
* @return [ UNCalendarNotificationTrigger* ]
*/
- (UNCalendarNotificationTrigger*) repeatingTriggerWithDateMatchingComponents
{
NSCalendar* cal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *date = [cal components:[self repeatInterval]
fromDate:[self fireDate]];
date.timeZone = [NSTimeZone defaultTimeZone];
return [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:YES];
}
/**
* A repeating trigger based on a calendar time intervals defined by the user.
*
* @return [ UNCalendarNotificationTrigger* ]
*/
- (UNCalendarNotificationTrigger*) repeatingTriggerWithCustomDateMatchingComponents
{
NSCalendar* cal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *date = [self customDateComponents];
date.calendar = cal;
date.timeZone = [NSTimeZone defaultTimeZone];
return [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:YES];
}
/**
* The time interval between the next fire date and now.
*
* @return [ double ]
*/
- (double) timeInterval
{
return MAX(0.01f, [self.fireDate timeIntervalSinceDate:[NSDate date]]);
}
/**
* The repeat interval for the notification.
*
* @return [ NSCalendarUnit ]
*/
- (NSCalendarUnit) repeatInterval
{
NSString* interval = [dict objectForKey:@"every"];
NSCalendarUnit units = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"minute"])
return NSCalendarUnitSecond;
if ([interval isEqualToString:@"hour"])
return NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"day"])
return NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"week"])
return NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"month"])
return NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
if ([interval isEqualToString:@"year"])
return NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
return units;
}
/**
* The repeat interval for the notification.
*
* @return [ NSDateComponents* ]
*/
- (NSDateComponents*) customDateComponents
{
NSDateComponents* date = [[NSDateComponents alloc] init];
NSDictionary* every = [dict objectForKey:@"every"];
for (NSString* key in every) {
long value = [[every valueForKey:key] longValue];
if ([key isEqualToString:@"second"]) {
date.second = value;
} else
if ([key isEqualToString:@"minute"]) {
date.minute = value;
} else
if ([key isEqualToString:@"hour"]) {
date.hour = value;
} else
if ([key isEqualToString:@"day"]) {
date.day = value;
} else
if ([key isEqualToString:@"weekday"]) {
date.weekday = value;
} else
if ([key isEqualToString:@"weekdayOrdinal"]) {
date.weekdayOrdinal = value;
} else
if ([key isEqualToString:@"week"]) {
date.weekOfYear = value;
} else
if ([key isEqualToString:@"weekOfMonth"]) {
date.weekOfMonth = value;
} else
if ([key isEqualToString:@"month"]) {
date.month = value;
} else
if ([key isEqualToString:@"quarter"]) {
date.quarter = value;
} else
if ([key isEqualToString:@"year"]) {
date.year = value;
}
}
return date;
}
/**
* Convert an assets path to an valid sound name attribute.
*
* @param [ NSString* ] path A relative assets file path.
*
* @return [ NSString* ]
*/
- (NSString*) soundNameForAsset:(NSString*)path
{
return [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"www"];
}
/**
* Convert a ressource path to an valid sound name attribute.
*
* @param [ NSString* ] path A relative ressource file path.
*
* @return [ NSString* ]
*/
- (NSString*) soundNameForResource:(NSString*)path
{
return [path pathComponents].lastObject;
}
/**
* URL for the specified attachment path.
*
* @param [ NSString* ] path Absolute/relative path or a base64 data.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAttachmentPath:(NSString*)path
{
if ([path hasPrefix:@"file:///"])
{
return [self urlForFile:path];
}
else if ([path hasPrefix:@"res:"])
{
return [self urlForResource:path];
}
else if ([path hasPrefix:@"file://"])
{
return [self urlForAsset:path];
}
else if ([path hasPrefix:@"app://"])
{
return [self urlForAppInternalPath:path];
}
else if ([path hasPrefix:@"base64:"])
{
return [self urlFromBase64:path];
}
NSFileManager* fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:path]){
NSLog(@"File not found: %@", path);
}
return [NSURL fileURLWithPath:path];
}
/**
* URL to an absolute file path.
*
* @param [ NSString* ] path An absolute file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForFile:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"file://"
withString:@""];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL to a resource file.
*
* @param [ NSString* ] path A relative file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForResource:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* bundlePath = [mainBundle bundlePath];
if ([path isEqualToString:@"res://icon"]) {
path = @"res://AppIcon60x60@3x.png";
}
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"res:/"
withString:@""];
absPath = [bundlePath stringByAppendingString:absPath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL to an asset file.
*
* @param path A relative www file path.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAsset:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* bundlePath = [mainBundle bundlePath];
NSString* absPath;
absPath = [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"/www"];
absPath = [bundlePath stringByAppendingString:absPath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL for an internal app path.
*
* @param [ NSString* ] path A relative file path from main bundle dir.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForAppInternalPath:(NSString*)path
{
NSFileManager* fm = [NSFileManager defaultManager];
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* absPath = [mainBundle bundlePath];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return [NSURL fileURLWithPath:absPath];
}
/**
* URL for a base64 encoded string.
*
* @param [ NSString* ] base64String Base64 encoded string.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlFromBase64:(NSString*)base64String
{
NSString *filename = [self getBasenameFromAttachmentPath:base64String];
NSUInteger length = [base64String length];
NSRegularExpression *regex;
NSString *dataString;
regex = [NSRegularExpression regularExpressionWithPattern:@"^base64:[^/]+.."
options:NSRegularExpressionCaseInsensitive
error:Nil];
dataString = [regex stringByReplacingMatchesInString:base64String
options:0
range:NSMakeRange(0, length)
withTemplate:@""];
NSData* data = [[NSData alloc] initWithBase64EncodedString:dataString
options:0];
return [self urlForData:data withFileName:filename];
}
/**
* Extract the attachments basename.
*
* @param [ NSString* ] path The file path or base64 data.
*
* @return [ NSString* ]
*/
- (NSString*) getBasenameFromAttachmentPath:(NSString*)path
{
if ([path hasPrefix:@"base64:"]) {
NSString* pathWithoutPrefix;
pathWithoutPrefix = [path stringByReplacingOccurrencesOfString:@"base64:"
withString:@""];
return [pathWithoutPrefix substringToIndex:
[pathWithoutPrefix rangeOfString:@"//"].location];
}
return path;
}
/**
* Write the data into a temp file.
*
* @param [ NSData* ] data The data to save to file.
* @param [ NSString* ] name The name of the file.
*
* @return [ NSURL* ]
*/
- (NSURL*) urlForData:(NSData*)data withFileName:(NSString*) filename
{
NSFileManager* fm = [NSFileManager defaultManager];
NSString* tempDir = NSTemporaryDirectory();
[fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES
attributes:NULL
error:NULL];
NSString* absPath = [tempDir stringByAppendingPathComponent:filename];
NSURL* url = [NSURL fileURLWithPath:absPath];
[data writeToURL:url atomically:NO];
if (![fm fileExistsAtPath:absPath]) {
NSLog(@"File not found: %@", absPath);
}
return url;
}
@end
......@@ -21,12 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPNotificationOptions.h"
@import UserNotifications;
@interface UNNotificationRequest (APPLocalNotification)
// The options provided by the plug-in
- (APPLocalNotificationOptions*) options;
- (APPNotificationOptions*) options;
// Encode the user info dict to JSON
- (NSString*) encodeToJSON;
......
......@@ -21,9 +21,9 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UNMutableNotificationContent+APPLocalNotification.h"
#import "APPLocalNotificationOptions.h"
#import "APPNotificationOptions.h"
#import "UNNotificationRequest+APPLocalNotification.h"
#import "APPNotificationContent.h"
#import <objc/runtime.h>
@import UserNotifications;
......@@ -35,7 +35,7 @@ static char optionsKey;
/**
* Get associated option object
*/
- (APPLocalNotificationOptions*) getOptions
- (APPNotificationOptions*) getOptions
{
return objc_getAssociatedObject(self, &optionsKey);
}
......@@ -43,7 +43,7 @@ static char optionsKey;
/**
* Set associated option object
*/
- (void) setOptions:(APPLocalNotificationOptions*)options
- (void) setOptions:(APPNotificationOptions*)options
{
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
......@@ -52,12 +52,12 @@ static char optionsKey;
/**
* The options provided by the plug-in.
*/
- (APPLocalNotificationOptions*) options
- (APPNotificationOptions*) options
{
APPLocalNotificationOptions* options = [self getOptions];
APPNotificationOptions* options = [self getOptions];
if (!options) {
options = [[APPLocalNotificationOptions alloc]
options = [[APPNotificationOptions alloc]
initWithDict:[self.content userInfo]];
[self setOptions:options];
......
......@@ -21,10 +21,12 @@
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UNMutableNotificationContent+APPLocalNotification.h"
#import "APPNotificationContent.h"
@interface UNUserNotificationCenter (APPLocalNotification)
extern NSString * const kAPPGeneralCategory;
typedef NS_ENUM(NSUInteger, APPNotificationType) {
NotifcationTypeAll = 0,
NotifcationTypeScheduled = 1,
......@@ -36,6 +38,8 @@ typedef NS_ENUM(NSUInteger, APPNotificationType) {
@property (readonly, getter=getNotifications) NSArray* localNotifications;
@property (readonly, getter=getNotificationIds) NSArray* localNotificationIds;
- (void) registerGeneralNotificationCategory;
// List of all notification IDs from given type
- (NSArray*) getNotificationIdsByType:(APPNotificationType)type;
......
......@@ -26,9 +26,32 @@
@import UserNotifications;
NSString * const kAPPGeneralCategory = @"GENERAL";
@implementation UNUserNotificationCenter (APPLocalNotification)
#pragma mark -
#pragma mark NotificationCategory
/**
* Register general notification category to listen for dismiss actions.
*
* @return [ Void ]
*/
- (void) registerGeneralNotificationCategory
{
UNNotificationCategory* category;
category = [UNNotificationCategory
categoryWithIdentifier:kAPPGeneralCategory
actions:@[]
intentIdentifiers:@[]
options:UNNotificationCategoryOptionCustomDismissAction];
[self setNotificationCategories:[NSSet setWithObjects:category, nil]];
}
#pragma mark -
#pragma mark LocalNotifications
/**
......
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
@interface APPLocalNotification9 : CDVPlugin
// Execute all queued events
- (void) deviceready:(CDVInvokedUrlCommand*)command;
// Inform if the app has the permission to show notifications
- (void) hasPermission:(CDVInvokedUrlCommand*)command;
// Register permission to show notifications
- (void) registerPermission:(CDVInvokedUrlCommand*)command;
// Schedule set of notifications
- (void) schedule:(CDVInvokedUrlCommand*)command;
// Update set of notifications
- (void) update:(CDVInvokedUrlCommand*)command;
// Cancel set of notifications
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// Clear set of notifications
- (void) clear:(CDVInvokedUrlCommand*)command;
// Clear all notifications
- (void) clearAll:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is present
- (void) isPresent:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is scheduled
- (void) isScheduled:(CDVInvokedUrlCommand*)command;
// If a notification with an ID is triggered
- (void) isTriggered:(CDVInvokedUrlCommand*)command;
// List all ids from all local notifications
- (void) getAllIds:(CDVInvokedUrlCommand*)command;
// List all ids from all pending notifications
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command;
// List all ids from all triggered notifications
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command;
// Propertys for given local notification
- (void) getSingle:(CDVInvokedUrlCommand*)command;
// Propertya for given scheduled notification
- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command;
// Propertys for given triggered notification
- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command;
// Property list for given local notifications
- (void) getAll:(CDVInvokedUrlCommand*)command;
// Property list for given scheduled notifications
- (void) getScheduled:(CDVInvokedUrlCommand*)command;
// Property list for given triggered notifications
- (void) getTriggered:(CDVInvokedUrlCommand*)command;
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotification.ios9.h"
#import "APPLocalNotificationOptions.ios9.h"
#import "UIApplication+APPLocalNotification.ios9.h"
#import "UILocalNotification+APPLocalNotification.ios9.h"
@interface APPLocalNotification9 ()
// Retrieves the application state
@property (readonly, getter=applicationState) NSString* applicationState;
// All events will be queued until deviceready has been fired
@property (readwrite, assign) BOOL deviceready;
// Event queue
@property (readonly, nonatomic, retain) NSMutableArray* eventQueue;
// Needed when calling `registerPermission`
@property (nonatomic, retain) CDVInvokedUrlCommand* command;
@end
@implementation APPLocalNotification9
@synthesize deviceready, eventQueue;
#pragma mark -
#pragma mark Interface
/**
* Execute all queued events.
*/
- (void) deviceready:(CDVInvokedUrlCommand*)command
{
deviceready = YES;
for (NSString* js in eventQueue) {
[self.commandDelegate evalJs:js];
}
[eventQueue removeAllObjects];
}
/**
* Schedule a set of notifications.
*
* @param properties
* A dict of properties for each notification
*/
- (void) schedule:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
for (NSDictionary* options in notifications) {
UILocalNotification* notification;
notification = [[UILocalNotification alloc]
initWithOptions:options];
[self scheduleLocalNotification:[notification copy]];
[self fireEvent:@"schedule" notification:notification];
if (notifications.count > 1) {
[NSThread sleepForTimeInterval:0.01];
}
}
[self execCallback:command];
}];
}
/**
* Update a set of notifications.
*
* @param properties
* A dict of properties for each notification
*/
- (void) update:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
for (NSDictionary* options in notifications) {
NSNumber* id = [options objectForKey:@"id"];
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self updateLocalNotification:[notification copy]
withOptions:options];
[self fireEvent:@"update" notification:notification];
if (notifications.count > 1) {
[NSThread sleepForTimeInterval:0.01];
}
}
[self execCallback:command];
}];
}
/**
* Cancel a set of notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) cancel:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
for (NSNumber* id in command.arguments) {
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
[self execCallback:command];
}];
}
/**
* Cancel all local notifications.
*/
- (void) cancelAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self cancelAllLocalNotifications];
[self fireEvent:@"cancelall"];
[self execCallback:command];
}];
}
/**
* Clear a set of notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) clear:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
for (NSNumber* id in command.arguments) {
UILocalNotification* notification;
notification = [self.app localNotificationWithId:id];
if (!notification)
continue;
[self.app clearLocalNotification:notification];
[self fireEvent:@"clear" notification:notification];
}
[self execCallback:command];
}];
}
/**
* Clear all local notifications.
*/
- (void) clearAll:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
[self clearAllLocalNotifications];
[self fireEvent:@"clearall"];
[self execCallback:command];
}];
}
/**
* If a notification by ID is present.
*
* @param id
* The ID of the notification
*/
- (void) isPresent:(CDVInvokedUrlCommand *)command
{
[self isPresent:command type:NotifcationTypeAll];
}
/**
* If a notification by ID is scheduled.
*
* @param id
* The ID of the notification
*/
- (void) isScheduled:(CDVInvokedUrlCommand*)command
{
[self isPresent:command type:NotifcationTypeScheduled];
}
/**
* Check if a notification with an ID is triggered.
*
* @param id
* The ID of the notification
*/
- (void) isTriggered:(CDVInvokedUrlCommand*)command
{
[self isPresent:command type:NotifcationTypeTriggered];
}
/**
* Check if a notification with an ID exists.
*
* @param type
* The notification life cycle type
*/
- (void) isPresent:(CDVInvokedUrlCommand*)command
type:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSNumber* id = [command argumentAtIndex:0];
BOOL exist;
CDVPluginResult* result;
if (type == NotifcationTypeAll) {
exist = [self.app localNotificationExist:id];
} else {
exist = [self.app localNotificationExist:id type:type];
}
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:exist];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* List all ids from all local notifications.
*/
- (void) getAllIds:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeAll];
}
/**
* List all ids from all pending notifications.
*/
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeScheduled];
}
/**
* List all ids from all triggered notifications.
*/
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command
{
[self getIds:command byType:NotifcationTypeTriggered];
}
/**
* List of ids for given local notifications.
*
* @param type
* Notification life cycle type
* @param ids
* The IDs of the notifications
*/
- (void) getIds:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
CDVPluginResult* result;
NSArray* ids;
if (type == NotifcationTypeAll) {
ids = [self.app localNotificationIds];
} else {
ids = [self.app localNotificationIdsByType:type];
}
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:ids];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Propertys for given local notification.
*/
- (void) getSingle:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeAll];
}
/**
* Propertya for given scheduled notification.
*/
- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeScheduled];
}
// Propertys for given triggered notification
- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command
{
[self getOption:command byType:NotifcationTypeTriggered];
}
/**
* Property list for given local notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) getAll:(CDVInvokedUrlCommand*)command
{
[self getOptions:command byType:NotifcationTypeAll];
}
/**
* Property list for given scheduled notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) getScheduled:(CDVInvokedUrlCommand*)command
{
[self getOptions:command byType:NotifcationTypeScheduled];
}
/**
* Property list for given triggered notifications.
*
* @param ids
* The IDs of the notifications
*/
- (void) getTriggered:(CDVInvokedUrlCommand *)command
{
[self getOptions:command byType:NotifcationTypeTriggered];
}
/**
* Propertys for given triggered notification.
*
* @param type
* Notification life cycle type
* @param ids
* The ID of the notification
*/
- (void) getOption:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
CDVPluginResult* result;
if (type == NotifcationTypeAll) {
notifications = [self.app localNotificationOptionsById:ids];
}
else {
notifications = [self.app localNotificationOptionsByType:type
andId:ids];
}
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:[notifications firstObject]];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Property list for given triggered notifications.
*
* @param type
* Notification life cycle type
* @param ids
* The IDs of the notifications
*/
- (void) getOptions:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type;
{
[self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments;
NSArray* notifications;
CDVPluginResult* result;
if (type == NotifcationTypeAll && ids.count == 0) {
notifications = [self.app localNotificationOptions];
}
else if (type == NotifcationTypeAll) {
notifications = [self.app localNotificationOptionsById:ids];
}
else if (ids.count == 0) {
notifications = [self.app localNotificationOptionsByType:type];
}
else {
notifications = [self.app localNotificationOptionsByType:type
andId:ids];
}
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:notifications];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Inform if the app has the permission to show
* badges and local notifications.
*/
- (void) hasPermission:(CDVInvokedUrlCommand*)command
{
[self.commandDelegate runInBackground:^{
CDVPluginResult* result;
BOOL hasPermission;
hasPermission = [self.app hasPermissionToScheduleLocalNotifications];
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:hasPermission];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}];
}
/**
* Ask for permission to show badges.
*/
- (void) registerPermission:(CDVInvokedUrlCommand*)command
{
if ([[UIApplication sharedApplication]
respondsToSelector:@selector(registerUserNotificationSettings:)])
{
_command = command;
[self.commandDelegate runInBackground:^{
[self.app registerPermissionToScheduleLocalNotifications];
}];
} else {
[self hasPermission:command];
}
}
#pragma mark -
#pragma mark Core Logic
/**
* Schedule the local notification.
*/
- (void) scheduleLocalNotification:(UILocalNotification*)notification
{
[self cancelForerunnerLocalNotification:notification];
[self.app scheduleLocalNotification:notification];
}
/**
* Update the local notification.
*/
- (void) updateLocalNotification:(UILocalNotification*)notification
withOptions:(NSDictionary*)newOptions
{
NSMutableDictionary* options = [notification.userInfo mutableCopy];
[options addEntriesFromDictionary:newOptions];
[options setObject:[NSDate date] forKey:@"updatedAt"];
notification = [[UILocalNotification alloc]
initWithOptions:options];
[self scheduleLocalNotification:notification];
}
/**
* Cancel all local notifications.
*/
- (void) cancelAllLocalNotifications
{
[self.app cancelAllLocalNotifications];
[self.app setApplicationIconBadgeNumber:0];
}
/**
* Clear all local notifications.
*/
- (void) clearAllLocalNotifications
{
[self.app clearAllLocalNotifications];
[self.app setApplicationIconBadgeNumber:0];
}
/**
* Cancel a maybe given forerunner with the same ID.
*/
- (void) cancelForerunnerLocalNotification:(UILocalNotification*)notification
{
NSNumber* id = notification.options.id;
UILocalNotification* forerunner;
forerunner = [self.app localNotificationWithId:id];
if (!forerunner)
return;
[self.app cancelLocalNotification:forerunner];
}
/**
* Cancels all non-repeating local notification older then
* a specific amount of seconds
*/
- (void) cancelAllNotificationsWhichAreOlderThen:(float)seconds
{
NSArray* notifications;
notifications = [self.app localNotifications];
for (UILocalNotification* notification in notifications)
{
if (![notification isRepeating]
&& notification.timeIntervalSinceFireDate > seconds)
{
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
}
}
#pragma mark -
#pragma mark Delegates
/**
* Calls the cancel or trigger event after a local notification was received.
* Cancels the local notification if autoCancel was set to true.
*/
- (void) didReceiveLocalNotification:(NSNotification*)localNotification
{
UILocalNotification* notification = [localNotification object];
if ([notification userInfo] == NULL || [notification wasUpdated])
return;
NSTimeInterval timeInterval = [notification timeIntervalSinceLastTrigger];
NSString* event = timeInterval < 0.2 && deviceready ? @"trigger" : @"click";
[self fireEvent:event notification:notification];
if (![event isEqualToString:@"click"])
return;
if ([notification isRepeating]) {
[self fireEvent:@"clear" notification:notification];
} else {
[self.app cancelLocalNotification:notification];
[self fireEvent:@"cancel" notification:notification];
}
}
/**
* Called when app has started
* (by clicking on a local notification).
*/
- (void) didFinishLaunchingWithOptions:(NSNotification*)notification
{
NSDictionary* launchOptions = [notification userInfo];
UILocalNotification* localNotification;
localNotification = [launchOptions objectForKey:
UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
[self didReceiveLocalNotification:
[NSNotification notificationWithName:CDVLocalNotification
object:localNotification]];
}
}
/**
* Called on otification settings registration is completed.
*/
- (void) didRegisterUserNotificationSettings:(UIUserNotificationSettings*)settings
{
if (_command) {
[self hasPermission:_command];
_command = NULL;
}
}
#pragma mark -
#pragma mark Life Cycle
/**
* Registers obervers after plugin was initialized.
*/
- (void) pluginInitialize
{
eventQueue = [[NSMutableArray alloc] init];
}
/**
* Clears all single repeating notifications which are older then 5 days
* before the app terminates.
*/
- (void) onAppTerminate
{
[self cancelAllNotificationsWhichAreOlderThen:432000];
}
#pragma mark -
#pragma mark Helper
/**
* Retrieves the application state
*
* @return
* Either "background" or "foreground"
*/
- (NSString*) applicationState
{
UIApplicationState state = [self.app applicationState];
bool isActive = state == UIApplicationStateActive;
return isActive ? @"foreground" : @"background";
}
/**
* Simply invokes the callback without any parameter.
*/
- (void) execCallback:(CDVInvokedUrlCommand*)command
{
CDVPluginResult *result = [CDVPluginResult
resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result
callbackId:command.callbackId];
}
/**
* Short hand for shared application instance.
*/
- (UIApplication*) app
{
return [UIApplication sharedApplication];
}
/**
* Fire general event.
*/
- (void) fireEvent:(NSString*)event
{
[self fireEvent:event notification:NULL];
}
/**
* Fire event for local notification.
*/
- (void) fireEvent:(NSString*)event notification:(UILocalNotification*)notification
{
NSString* js;
NSString* params = [NSString stringWithFormat:
@"\"%@\"", self.applicationState];
if (notification) {
NSString* args = [notification encodeToJSON];
params = [NSString stringWithFormat:
@"%@,'%@'",
args, self.applicationState];
}
js = [NSString stringWithFormat:
@"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
event, params];
if (deviceready) {
[self.commandDelegate evalJs:js];
} else {
[self.eventQueue addObject:js];
}
}
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "APPLocalNotificationOptions.ios9.h"
@interface APPLocalNotificationOptions9 ()
// The dictionary which contains all notification properties
@property(nonatomic, retain) NSDictionary* dict;
@end
@implementation APPLocalNotificationOptions9
@synthesize dict;
#pragma mark -
#pragma mark Initialization
/**
* Initialize the object with the given options when calling on JS side:
* notification.local.add(options)
*/
- (id) initWithDict:(NSDictionary*)dictionary
{
self = [self init];
self.dict = dictionary;
return self;
}
#pragma mark -
#pragma mark Attributes
/**
* The notification's ID.
*/
- (NSNumber*) id
{
NSInteger id = [[dict objectForKey:@"id"] integerValue];
return [NSNumber numberWithInteger:id];
}
/**
* The notification's title.
*/
- (NSString*) title
{
return [dict objectForKey:@"title"];
}
/**
* The notification's message.
*/
- (NSString*) text
{
return [dict objectForKey:@"text"];
}
/**
* The notification's badge number.
*/
- (NSInteger) badgeNumber
{
return [[dict objectForKey:@"badge"] intValue];
}
#pragma mark -
#pragma mark Complex Attributes
/**
* The notification's alert body.
*/
- (NSString*) alertBody
{
NSString* title = [self title];
NSString* msg = [self text];
NSString* alertBody = msg;
if (![self stringIsNullOrEmpty:title])
{
alertBody = [NSString stringWithFormat:@"%@\n%@",
title, msg];
}
return alertBody;
}
/**
* The notification's sound path.
*/
- (NSString*) soundName
{
NSString* path = [dict objectForKey:@"sound"];
if ([self stringIsNullOrEmpty:path])
return NULL;
if ([path isEqualToString:@"res://platform_default"])
return UILocalNotificationDefaultSoundName;
if ([path hasPrefix:@"file:/"])
return [self soundNameForAsset:path];
if ([path hasPrefix:@"res:"])
return [self soundNameForResource:path];
return NULL;
}
/**
* The notification's fire date.
*/
- (NSDate*) fireDate
{
double timestamp = [[dict objectForKey:@"at"]
doubleValue];
return [NSDate dateWithTimeIntervalSince1970:timestamp];
}
/**
* The notification's repeat interval.
*/
- (NSCalendarUnit) repeatInterval
{
NSString* interval = [dict objectForKey:@"every"];
if ([self stringIsNullOrEmpty:interval]) {
return NSCalendarUnitEra;
}
else if ([interval isEqualToString:@"second"]) {
return NSCalendarUnitSecond;
}
else if ([interval isEqualToString:@"minute"]) {
return NSCalendarUnitMinute;
}
else if ([interval isEqualToString:@"hour"]) {
return NSCalendarUnitHour;
}
else if ([interval isEqualToString:@"day"]) {
return NSCalendarUnitDay;
}
else if ([interval isEqualToString:@"week"]) {
return NSCalendarUnitWeekOfYear;
}
else if ([interval isEqualToString:@"month"]) {
return NSCalendarUnitMonth;
}
else if ([interval isEqualToString:@"quarter"]) {
return NSCalendarUnitQuarter;
}
else if ([interval isEqualToString:@"year"]) {
return NSCalendarUnitYear;
}
return NSCalendarUnitEra;
}
#pragma mark -
#pragma mark Methods
/**
* The notification's user info dict.
*/
- (NSDictionary*) userInfo
{
if ([dict objectForKey:@"updatedAt"]) {
NSMutableDictionary* data = [dict mutableCopy];
[data removeObjectForKey:@"updatedAt"];
return data;
}
return dict;
}
/**
* If it's a repeating notification.
*/
- (BOOL) isRepeating
{
NSCalendarUnit interval = self.repeatInterval;
return !(interval == NSCalendarUnitEra || interval == 0);
}
#pragma mark -
#pragma mark Helpers
/**
* Convert relative path to valid sound name attribute.
*/
- (NSString*) soundNameForAsset:(NSString*)path
{
return [path stringByReplacingOccurrencesOfString:@"file:/"
withString:@"www"];
}
/**
* Convert resource path to valid sound name attribute.
*/
- (NSString*) soundNameForResource:(NSString*)path
{
return [path pathComponents].lastObject;
}
/**
* If the string is empty.
*/
- (BOOL) stringIsNullOrEmpty:(NSString*)str
{
if (str == (NSString*)[NSNull null])
return YES;
if ([str isEqualToString:@""])
return YES;
return NO;
}
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UIApplication+APPLocalNotification.ios9.h"
#import "UILocalNotification+APPLocalNotification.ios9.h"
@implementation UIApplication (APPLocalNotification)
#pragma mark -
#pragma mark Permissions
/**
* If the app has the permission to schedule local notifications.
*/
- (BOOL) hasPermissionToScheduleLocalNotifications
{
if ([[UIApplication sharedApplication]
respondsToSelector:@selector(registerUserNotificationSettings:)])
{
UIUserNotificationType types;
UIUserNotificationSettings *settings;
settings = [[UIApplication sharedApplication]
currentUserNotificationSettings];
types = UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;
return (settings.types & types);
} else {
return YES;
}
}
/**
* Ask for permission to schedule local notifications.
*/
- (void) registerPermissionToScheduleLocalNotifications
{
if ([[UIApplication sharedApplication]
respondsToSelector:@selector(registerUserNotificationSettings:)])
{
UIUserNotificationType types;
UIUserNotificationSettings *settings;
settings = [[UIApplication sharedApplication]
currentUserNotificationSettings];
types = settings.types|UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;
settings = [UIUserNotificationSettings settingsForTypes:types
categories:nil];
[[UIApplication sharedApplication]
registerUserNotificationSettings:settings];
}
}
#pragma mark -
#pragma mark LocalNotifications
/**
* List of all local notifications which have been added
* but not yet removed from the notification center.
*/
- (NSArray*) localNotifications
{
NSArray* scheduledNotifications = self.scheduledLocalNotifications;
NSMutableArray* notifications = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in scheduledNotifications)
{
if (notification) {
[notifications addObject:notification];
}
}
return notifications;
}
/**
* List of all triggered local notifications which have been scheduled
* and not yet removed the notification center.
*/
- (NSArray*) triggeredLocalNotifications
{
NSArray* notifications = self.localNotifications;
NSMutableArray* triggeredNotifications = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
if ([notification isTriggered]) {
[triggeredNotifications addObject:notification];
}
}
return triggeredNotifications;
}
/**
* List of all local notifications IDs.
*/
- (NSArray*) localNotificationIds
{
NSArray* notifications = self.localNotifications;
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[ids addObject:notification.options.id];
}
return ids;
}
/**
* List of all local notifications IDs from given type.
*
* @param type
* Notification life cycle type
*/
- (NSArray*) localNotificationIdsByType:(APPNotificationType)type
{
NSArray* notifications = self.localNotifications;
NSMutableArray* ids = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
if (notification.type == type) {
[ids addObject:notification.options.id];
}
}
return ids;
}
/*
* If local notification with ID exists.
*
* @param id
* Notification ID
*/
- (BOOL) localNotificationExist:(NSNumber*)id
{
return [self localNotificationWithId:id] != NULL;
}
/* If local notification with ID and type exists
*
* @param id
* Notification ID
* @param type
* Notification life cycle type
*/
- (BOOL) localNotificationExist:(NSNumber*)id type:(APPNotificationType)type
{
return [self localNotificationWithId:id andType:type] != NULL;
}
/**
* Get local notification with ID.
*
* @param id
* Notification ID
*/
- (UILocalNotification*) localNotificationWithId:(NSNumber*)id
{
NSArray* notifications = self.localNotifications;
for (UILocalNotification* notification in notifications)
{
NSString* fid = [NSString stringWithFormat:@"%@", notification.options.id];
if ([fid isEqualToString:[id stringValue]]) {
return notification;
}
}
return NULL;
}
/*
* Get local notification with ID and type.
*
* @param id
* Notification ID
* @param type
* Notification life cycle type
*/
- (UILocalNotification*) localNotificationWithId:(NSNumber*)id andType:(APPNotificationType)type
{
UILocalNotification* notification = [self localNotificationWithId:id];
if (notification && notification.type == type)
return notification;
return NULL;
}
/**
* List of properties from all notifications.
*/
- (NSArray*) localNotificationOptions
{
NSArray* notifications = self.localNotifications;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
[options addObject:notification.options.userInfo];
}
return options;
}
/**
* List of properties from all local notifications from given type.
*
* @param type
* Notification life cycle type
*/
- (NSArray*) localNotificationOptionsByType:(APPNotificationType)type
{
NSArray* notifications = self.localNotifications;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (UILocalNotification* notification in notifications)
{
if (notification.type == type) {
[options addObject:notification.options.userInfo];
}
}
return options;
}
/**
* List of properties from given local notifications.
*
* @param ids
* Notification IDs
*/
- (NSArray*) localNotificationOptionsById:(NSArray*)ids
{
UILocalNotification* notification;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (NSNumber* id in ids)
{
notification = [self localNotificationWithId:id];
if (notification) {
[options addObject:notification.options.userInfo];
}
}
return options;
}
/**
* List of properties from given local notifications.
*
* @param type
* Notification life cycle type
* @param ids
* Notification IDs
*/
- (NSArray*) localNotificationOptionsByType:(APPNotificationType)type andId:(NSArray*)ids
{
UILocalNotification* notification;
NSMutableArray* options = [[NSMutableArray alloc] init];
for (NSNumber* id in ids)
{
notification = [self localNotificationWithId:id];
if (notification && notification.type == type) {
[options addObject:notification.options.userInfo];
}
}
return options;
}
/*
* Clear all local notfications.
*/
- (void) clearAllLocalNotifications
{
NSArray* notifications = self.triggeredLocalNotifications;
for (UILocalNotification* notification in notifications) {
[self clearLocalNotification:notification];
}
}
/*
* Clear single local notfication.
*
* @param notification
* The local notification object
*/
- (void) clearLocalNotification:(UILocalNotification*)notification
{
[self cancelLocalNotification:notification];
if ([notification isRepeating]) {
notification.fireDate = notification.options.fireDate;
[self scheduleLocalNotification:notification];
};
}
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
#import "UILocalNotification+APPLocalNotification.ios9.h"
#import "APPLocalNotificationOptions.ios9.h"
#import <objc/runtime.h>
static char optionsKey;
NSInteger const APPLocalNotificationTypeScheduled = 1;
NSInteger const APPLocalNotificationTypeTriggered = 2;
@implementation UILocalNotification (APPLocalNotification)
#pragma mark -
#pragma mark Init
/**
* Initialize a local notification with the given options when calling on JS side:
* notification.local.add(options)
*/
- (id) initWithOptions:(NSDictionary*)dict
{
self = [self init];
[self setUserInfo:dict];
[self __init];
return self;
}
/**
* Applies the given options when calling on JS side:
* notification.local.add(options)
*/
- (void) __init
{
APPLocalNotificationOptions9* options = self.options;
self.fireDate = options.fireDate;
self.timeZone = [NSTimeZone defaultTimeZone];
self.applicationIconBadgeNumber = options.badgeNumber;
self.repeatInterval = options.repeatInterval;
self.alertBody = options.alertBody;
self.soundName = options.soundName;
if ([self wasInThePast]) {
self.fireDate = [NSDate date];
}
}
#pragma mark -
#pragma mark Methods
/**
* The options provided by the plug-in.
*/
- (APPLocalNotificationOptions9*) options
{
APPLocalNotificationOptions9* options = [self getOptions];
if (!options) {
options = [[APPLocalNotificationOptions9 alloc]
initWithDict:[self userInfo]];
[self setOptions:options];
}
return options;
}
/**
* Get associated option object
*/
- (APPLocalNotificationOptions9*) getOptions
{
return objc_getAssociatedObject(self, &optionsKey);
}
/**
* Set associated option object
*/
- (void) setOptions:(APPLocalNotificationOptions9*)options
{
objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
/**
* The repeating interval in seconds.
*/
- (int) repeatIntervalInSeconds
{
switch (self.repeatInterval) {
case NSCalendarUnitMinute:
return 60;
case NSCalendarUnitHour:
return 60000;
case NSCalendarUnitDay:
case NSCalendarUnitWeekOfYear:
case NSCalendarUnitMonth:
case NSCalendarUnitYear:
return 86400;
default:
return 1;
}
}
/**
* Timeinterval since fire date.
*/
- (double) timeIntervalSinceFireDate
{
NSDate* now = [NSDate date];
NSDate* fireDate = self.fireDate;
int timespan = [now timeIntervalSinceDate:fireDate];
return timespan;
}
/**
* Timeinterval since last trigger date.
*/
- (double) timeIntervalSinceLastTrigger
{
int timespan = [self timeIntervalSinceFireDate];
if ([self isRepeating]) {
timespan = timespan % [self repeatIntervalInSeconds];
}
return timespan;
}
/**
* Encode the user info dict to JSON.
*/
- (NSString*) encodeToJSON
{
NSString* json;
NSData* data;
NSMutableDictionary* obj = [self.userInfo mutableCopy];
[obj removeObjectForKey:@"updatedAt"];
if (obj == NULL || obj.count == 0)
return json;
data = [NSJSONSerialization dataWithJSONObject:obj
options:NSJSONWritingPrettyPrinted
error:NULL];
json = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
return [json stringByReplacingOccurrencesOfString:@"\n"
withString:@""];
}
#pragma mark -
#pragma mark State
/**
* If the fire date was in the past.
*/
- (BOOL) wasInThePast
{
return [self timeIntervalSinceLastTrigger] > 0;
}
// If the notification was already scheduled
- (BOOL) isScheduled
{
return [self isRepeating] || ![self wasInThePast];
}
/**
* If the notification was already triggered.
*/
- (BOOL) isTriggered
{
NSDate* now = [NSDate date];
NSDate* fireDate = self.fireDate;
bool isLaterThanFireDate = !([now compare:fireDate] == NSOrderedAscending);
return isLaterThanFireDate;
}
/**
* If the notification was updated.
*/
- (BOOL) wasUpdated
{
NSDate* now = [NSDate date];
NSDate* updatedAt = [self.userInfo objectForKey:@"updatedAt"];
if (updatedAt == NULL)
return NO;
int timespan = [now timeIntervalSinceDate:updatedAt];
return timespan < 1;
}
/**
* If it's a repeating notification.
*/
- (BOOL) isRepeating
{
return [self.options isRepeating];
}
/**
* Process state type of the local notification.
*/
- (APPNotificationType) type
{
return [self isTriggered] ? NotifcationTypeTriggered : NotifcationTypeScheduled;
}
@end
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -17,56 +13,60 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
var exec = require('cordova/exec');
/********
* CORE *
********/
/**
* Returns the default settings.
* Request permission to show notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return {Object}
* @return [ Void ]
*/
exports.getDefaults = function () {
return this._defaults;
exports.hasPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
};
/**
* Overwrite default settings.
* Request permission to show notifications.
*
* @param {Object} defaults
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
exports.requestPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
for (var key in defaults) {
if (newDefaults.hasOwnProperty(key)) {
defaults[key] = newDefaults[key];
}
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'request', []);
};
/**
* Schedule a new local notification.
*
* @param {Object} msgs
* The notification properties
* @param {Function} callback
* A function to be called after the notification has been canceled
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (msgs, callback, scope, args) {
var fn = function(granted) {
var fn = function (granted) {
if (!granted) return;
......@@ -85,55 +85,54 @@ exports.schedule = function (msgs, callback, scope, args) {
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.registerPermission(fn, this);
this.requestPermission(fn, this);
}
};
/**
* Update existing notifications specified by IDs in options.
*
* @param {Object} notifications
* The notification properties to update
* @param {Function} callback
* A function to be called after the notification has been updated
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/
exports.update = function (msgs, callback, scope, args) {
var fn = function(granted) {
if (!granted) return;
var notifications = Array.isArray(msgs) ? msgs : [msgs];
for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i];
this.convertProperties(notification);
}
this.exec('update', notifications, callback, scope);
};
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.registerPermission(fn, this);
}
};
// /**
// * Update existing notifications specified by IDs in options.
// *
// * @param {Object} notifications
// * The notification properties to update
// * @param {Function} callback
// * A function to be called after the notification has been updated
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.update = function (msgs, callback, scope, args) {
// var fn = function(granted) {
// if (!granted) return;
// var notifications = Array.isArray(msgs) ? msgs : [msgs];
// for (var i = 0; i < notifications.length; i++) {
// var notification = notifications[i];
// this.convertProperties(notification);
// }
// this.exec('update', notifications, callback, scope);
// };
// if (args && args.skipPermission) {
// fn.call(this, true);
// } else {
// this.registerPermission(fn, this);
// }
// };
/**
* Clear the specified notification.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A function to be called after the notification has been cleared
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
......@@ -143,26 +142,25 @@ exports.clear = function (ids, callback, scope) {
};
/**
* Clear all previously sheduled notifications.
* Clear all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A function to be called after all notifications have been cleared
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.exec('clearAll', null, callback, scope);
};
/**
* Cancel the specified notifications.
*
* @param {String[]} ids
* The IDs of the notifications
* @param {Function} callback
* A function to be called after the notifications has been canceled
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids];
......@@ -172,69 +170,66 @@ exports.cancel = function (ids, callback, scope) {
};
/**
* Remove all previously registered notifications.
* Cancel all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A function to be called after all notifications have been canceled
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.exec('cancelAll', null, callback, scope);
};
/**
* Check if a notification with an ID is present.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.exec('isPresent', id || 0, callback, scope);
this.exec('isPresent', id, callback, scope);
};
/**
* Check if a notification with an ID is scheduled.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.exec('isScheduled', id || 0, callback, scope);
this.exec('isScheduled', id, callback, scope);
};
/**
* Check if a notification with an ID was triggered.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.exec('isTriggered', id || 0, callback, scope);
this.exec('isTriggered', id, callback, scope);
};
/**
* List all local notification IDs.
* List of all notification ids.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.exec('getAllIds', null, callback, scope);
this.exec('ids', null, callback, scope);
};
/**
......@@ -245,39 +240,38 @@ exports.getIds = function () {
};
/**
* List all scheduled notification IDs.
* List of all scheduled notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.exec('getScheduledIds', null, callback, scope);
this.exec('scheduledIds', null, callback, scope);
};
/**
* List all triggered notification IDs.
* List of all triggered notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.exec('getTriggeredIds', null, callback, scope);
this.exec('triggeredIds', null, callback, scope);
};
/**
* Property list for given local notifications.
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
var args = Array.apply(null, arguments);
......@@ -291,37 +285,36 @@ exports.get = function () {
scope = args[2];
if (!Array.isArray(ids)) {
this.exec('getSingle', Number(ids), callback, scope);
this.exec('notification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getAll', ids, callback, scope);
this.exec('notifications', ids, callback, scope);
};
/**
* Property list for all local notifications.
* List for all notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.exec('getAll', null, callback, scope);
this.exec('notifications', null, callback, scope);
};
/**
* Property list for given scheduled notifications.
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function () {
var args = Array.apply(null, arguments);
......@@ -339,37 +332,34 @@ exports.getScheduled = function () {
}
if (!Array.isArray(ids)) {
this.exec('getSingleScheduled', Number(ids), callback, scope);
this.exec('scheduledNotification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getScheduled', ids, callback, scope);
this.exec('scheduledNotifications', ids, callback, scope);
};
/**
* Property list for all scheduled notifications.
* List of all scheduled notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.exec('getScheduled', null, callback, scope);
this.exec('scheduledNotifications', null, callback, scope);
};
/**
* Property list for given triggered notifications.
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function () {
var args = Array.apply(null, arguments);
......@@ -387,86 +377,59 @@ exports.getTriggered = function () {
}
if (!Array.isArray(ids)) {
this.exec('getSingleTriggered', Number(ids), callback, scope);
this.exec('triggeredNotification', Number(ids), callback, scope);
return;
}
ids = this.convertIds(ids);
this.exec('getTriggered', ids, callback, scope);
this.exec('triggeredNotifications', ids, callback, scope);
};
/**
* Property list for all triggered notifications.
* List of all triggered notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.exec('getTriggered', null, callback, scope);
this.exec('triggeredNotifications', null, callback, scope);
};
/**
* Informs if the app has the permission to show notifications.
* The (platform specific) default settings.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Object ]
*/
exports.hasPermission = function (callback, scope) {
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
exports.getDefaults = function () {
return this._defaults;
};
/**
* Register permission to show notifications if not already granted.
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Void ]
*/
exports.requestPermission = function (callback, scope) {
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
if (this._registered) {
return this.hasPermission(callback, scope);
} else {
this._registered = true;
for (var key in defaults) {
if (newDefaults.hasOwnProperty(key)) {
defaults[key] = newDefaults[key];
}
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'request', []);
};
/**********
* EVENTS *
**********/
/**
* Register callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param {Object?} scope
* The callback function's scope
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
......@@ -485,10 +448,10 @@ exports.on = function (event, callback, scope) {
/**
* Unregister callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
var listener = this._listener[event];
......
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -17,18 +13,11 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
var exec = require('cordova/exec'),
channel = require('cordova/channel');
/***********
* MEMBERS *
***********/
// Default values
exports._defaults = {
text: '',
......@@ -41,22 +30,13 @@ exports._defaults = {
at: undefined
};
// listener
// Listener
exports._listener = {};
// Registered permission flag
exports._registered = false;
/********
* UTIL *
********/
/**
* Merge platform specific properties into the default ones.
*
* @return {Object}
* The default properties for the platform
* @return [ Void ]
*/
exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults;
......@@ -70,19 +50,18 @@ exports.applyPlatformSpecificOptions = function () {
defaults.led = undefined;
defaults.color = undefined;
break;
case 'iOS':
defaults.attachments = undefined;
break;
}
return defaults;
};
/**
* Merge custom properties with the default values.
*
* @param {Object} options
* Set of custom values
* @param [ Object ] options Set of custom values.
*
* @retrun {Object}
* The merged property list
* @retrun [ Object ]
*/
exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults();
......@@ -126,11 +105,9 @@ exports.mergeWithDefaults = function (options) {
/**
* Convert the passed values to their required type.
*
* @param {Object} options
* Set of custom values
* @param [ Object ] options Properties to convert for.
*
* @retrun {Object}
* The converted property list
* @return [ Object ] The converted property list
*/
exports.convertProperties = function (options) {
......@@ -172,46 +149,33 @@ exports.convertProperties = function (options) {
options.data = JSON.stringify(options.data);
}
if (options.every) {
if (device.platform == 'iOS' && typeof options.every != 'string') {
options.every = this.getDefaults().every;
var warning = 'Every option is not a string: ' + options.id;
warning += '. Expects one of: second, minute, hour, day, week, ';
warning += 'month, year on iOS.';
console.warn(warning);
}
}
return options;
};
/**
* Create callback, which will be executed within a specific scope.
* Create a callback function to get executed within a specific scope.
*
* @param {Function} callbackFn
* The callback function
* @param {Object} scope
* The scope for the function
* @param [ Function ] fn The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return {Function}
* The new callback function
* @return [ Function ]
*/
exports.createCallbackFn = function (callbackFn, scope) {
exports.createCallbackFn = function (fn, scope) {
if (typeof callbackFn != 'function')
if (typeof fn != 'function')
return;
return function () {
callbackFn.apply(scope || this, arguments);
fn.apply(scope || this, arguments);
};
};
/**
* Convert the IDs to numbers.
*
* @param {String/Number[]} ids
* @param [ Array ] ids
*
* @return Array of Numbers
* @return [ Array<Number> ]
*/
exports.convertIds = function (ids) {
var convertedIds = [];
......@@ -226,10 +190,10 @@ exports.convertIds = function (ids) {
/**
* First found value for the given keys.
*
* @param {Object} options
* Object with key-value properties
* @param {String[]} keys*
* Key list
* @param [ Object ] options Object with key-value properties.
* @param [ *Array<String> ] keys List of keys.
*
* @return [ Object ]
*/
exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1);
......@@ -244,12 +208,12 @@ exports.getValueFor = function (options) {
};
/**
* Fire event with given arguments.
* Fire the event with given arguments.
*
* @param {String} event
* The event's name
* @param {args*}
* The callback's arguments
* @param [ String ] event The event's name.
* @param [ *Array] args The callback's arguments.
*
* @return [ Void]
*/
exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1),
......@@ -269,14 +233,12 @@ exports.fireEvent = function (event) {
/**
* Execute the native counterpart.
*
* @param {String} action
* The name of the action
* @param args[]
* Array of arguments
* @param {Function} callback
* The callback function
* @param {Object} scope
* The scope for the function
* @param [ String ] action The name of the action.
* @param [ Array ] args Array of arguments.
* @param [ Function] callback The callback function.
* @param [ Object ] scope The scope for the function.
*
* @return [ Void ]
*/
exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope),
......@@ -291,11 +253,6 @@ exports.exec = function (action, args, callback, scope) {
exec(fn, null, 'LocalNotification', action, params);
};
/*********
* HOOKS *
*********/
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered
......
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
......@@ -17,192 +13,159 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
/*************
* INTERFACE *
*************/
/**
* Returns the default settings.
* Request permission to show notifications.
*
* @return {Object}
*/
exports.getDefaults = function () {
return this.core.getDefaults();
};
/**
* Overwrite default settings.
*
* @param {Object} defaults
*/
exports.setDefaults = function (defaults) {
this.core.setDefaults(defaults);
};
/**
* Informs if the app has the permission to show notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @return [ Void ]
*/
exports.hasPermission = function (callback, scope) {
this.core.hasPermission(callback, scope);
};
/**
* Register permission to show notifications if not already granted.
* Request permission to show notifications.
*
* @param {Function} callback
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope);
};
/**
* Schedule a new local notification.
*
* @param {Object} notifications
* The notification properties
* @param {Function} callback
* A function to be called after the notification has been canceled
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (notifications, callback, scope, args) {
this.core.schedule(notifications, callback, scope, args);
};
/**
* Update existing notifications specified by IDs in options.
*
* @param {Object} notifications
* The notification properties to update
* @param {Function} callback
* A function to be called after the notification has been updated
* @param {Object?} scope
* The scope for the callback function
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/
exports.update = function (notifications, callback, scope, args) {
this.core.update(notifications, callback, scope, args);
};
// /**
// * Update existing notifications specified by IDs in options.
// *
// * @param {Object} notifications
// * The notification properties to update
// * @param {Function} callback
// * A function to be called after the notification has been updated
// * @param {Object?} scope
// * The scope for the callback function
// * @param {Object?} args
// * skipPermission:true schedules the notifications immediatly without
// * registering or checking for permission
// */
// exports.update = function (notifications, callback, scope, args) {
// this.core.update(notifications, callback, scope, args);
// };
/**
* Clear the specified notification.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A function to be called after the notification has been cleared
* @param {Object?} scope
* The scope for the callback function
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
this.core.clear(ids, callback, scope);
};
/**
* Clear all previously sheduled notifications.
* Clear all triggered notifications.
*
* @param {Function} callback
* A function to be called after all notifications have been cleared
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this.core.clearAll(callback, scope);
};
/**
* Cancel the specified notifications.
*
* @param {String[]} ids
* The IDs of the notifications
* @param {Function} callback
* A function to be called after the notifications has been canceled
* @param {Object?} scope
* The scope for the callback function
* Cancel the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
this.core.cancel(ids, callback, scope);
};
/**
* Remove all previously registered notifications.
* Cancel all scheduled notifications.
*
* @param {Function} callback
* A function to be called after all notifications have been canceled
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this.core.cancelAll(callback, scope);
};
/**
* Check if a notification with an ID is present.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
this.core.isPresent(id, callback, scope);
};
/**
* Check if a notification with an ID is scheduled.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.core.isScheduled(id, callback, scope);
};
/**
* Check if a notification with an ID was triggered.
*
* @param {String} id
* The ID of the notification
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.core.isTriggered(id, callback, scope);
};
/**
* List all local notification IDs.
* List of all notification ids.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getAllIds = function (callback, scope) {
this.core.getAllIds(callback, scope);
......@@ -216,148 +179,131 @@ exports.getIds = function () {
};
/**
* List all scheduled notification IDs.
* List of all scheduled notification IDs.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this.core.getScheduledIds(callback, scope);
};
/**
* List all triggered notification IDs.
* List of all triggered notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this.core.getTriggeredIds(callback, scope);
};
/**
* Property list for given local notifications.
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
this.core.get.apply(this.core, arguments);
exports.get = function (ids, callback, scope) {
this.core.get(ids, callback, scope);
};
/**
* Property list for all local notifications.
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this.core.getAll(callback, scope);
};
/**
* Property list for given scheduled notifications.
* List of scheduled notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduled = function () {
this.core.getScheduled.apply(this.core, arguments);
exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled(ids, callback, scope);
};
/**
* Property list for all scheduled notifications.
* List of all scheduled notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllScheduled = function (callback, scope) {
this.core.getAllScheduled(callback, scope);
};
/**
* Property list for given triggered notifications.
* List of triggered notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param {Number[]?} ids
* Set of notification IDs
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggered = function () {
this.core.getTriggered.apply(this.core, arguments);
exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered(ids, callback, scope);
};
/**
* Property list for all triggered notifications.
* List of all triggered notifications.
*
* @param {Function} callback
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getAllTriggered = function (callback, scope) {
this.core.getAllTriggered(callback, scope);
};
/****************
* DEPRECATIONS *
****************/
/**
* Schedule a new local notification.
* The (platform specific) default settings.
*
* @return [ Object ]
*/
exports.add = function () {
console.warn('Depreated: Please use `notification.local.schedule` instead.');
this.schedule.apply(this, arguments);
exports.getDefaults = function () {
return this.core.getDefaults();
};
/**
* Register permission to show notifications
* if not already granted.
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.promptForPermission = function () {
console.warn('Depreated: Please use `notification.local.registerPermission` instead.');
this.registerPermission.apply(this, arguments);
exports.setDefaults = function (defaults) {
this.core.setDefaults(defaults);
};
/**********
* EVENTS *
**********/
/**
* Register callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param {Object?} scope
* The callback function's scope
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
this.core.on(event, callback, scope);
......@@ -366,10 +312,10 @@ exports.on = function (event, callback, scope) {
/**
* Unregister callback for given event.
*
* @param {String} event
* The event's name
* @param {Function} callback
* The function to be exec as callback
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
this.core.un(event, callback);
......
......@@ -30,7 +30,7 @@
<body>
<div>
<div class="app">
<h1>Local Notification Example</h1>
<h1>Notification Example</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
......@@ -47,7 +47,7 @@
<a id="sched_multi" class="button orange">Multiple</a>
</div>
<div class="container">
<a id="sched_delay" class="button orange">Delayed</a>
<a id="sched_delayed" class="button orange">Delayed</a>
<a id="sched_interval" class="button orange">Interval</a>
</div>
<h2 class="section">Update</h2>
......@@ -85,7 +85,7 @@
<a id="triggered_ids" class="button grey">Triggered</a>
</div>
<div class="container">
<a id="all_ids" class="button grey">All</a>
<a id="ids" class="button grey">All</a>
</div>
<h2 class="section">Notifications</h2>
<div class="container">
......@@ -93,11 +93,11 @@
<a id="triggered_nots" class="button grey">Triggered</a>
</div>
<div class="container">
<a id="single_not" class="button grey">Single</a>
<a id="notification" class="button grey">Single</a>
<a id="multiple_nots" class="button grey">Multiple</a>
</div>
<div class="container">
<a id="all_nots" class="button grey">All</a>
<a id="notifications" class="button grey">All</a>
</div>
<h2 class="section">Defaults</h2>
<div class="container">
......
......@@ -36,6 +36,7 @@ var app = {
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.pluginInitialize();
app.bindNotificationEvents();
},
// Update DOM on a Received Event
receivedEvent: function(id) {
......@@ -52,14 +53,238 @@ var app = {
pluginInitialize: function() {
document.getElementById('granted').onclick = app.hasPermission;
document.getElementById('request').onclick = app.askPermission;
document.getElementById('sched_single').onclick = app.scheduleSingle;
document.getElementById('sched_multi').onclick = app.scheduleMultiple;
document.getElementById('sched_delayed').onclick = app.scheduleDelayed;
document.getElementById('sched_interval').onclick = app.scheduleInterval;
document.getElementById('clear_single').onclick = app.clearSingle;
document.getElementById('clear_multi').onclick = app.clearMulti;
document.getElementById('clear_all').onclick = app.clearAll;
document.getElementById('cancel_single').onclick = app.cancelSingle;
document.getElementById('cancel_multi').onclick = app.cancelMulti;
document.getElementById('cancel_all').onclick = app.cancelAll;
document.getElementById('present?').onclick = app.isPresent;
document.getElementById('scheduled?').onclick = app.isScheduled;
document.getElementById('triggered?').onclick = app.isTriggered;
document.getElementById('ids').onclick = app.ids;
document.getElementById('scheduled_ids').onclick = app.scheduledIds;
document.getElementById('triggered_ids').onclick = app.triggeredIds;
document.getElementById('scheduled_nots').onclick = app.scheduledNots;
document.getElementById('triggered_nots').onclick = app.triggeredNots;
document.getElementById('notification').onclick = app.notification;
document.getElementById('multiple_nots').onclick = app.multipleNots;
document.getElementById('notifications').onclick = app.notifications;
document.getElementById('defaults').onclick = app.setDefaultTitle;
},
// Check permissions to read accounts
hasPermission: function () {
cordova.plugins.notification.local.hasPermission(showToast);
cordova.plugins.notification.local.hasPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
},
// Request permissions to read accounts
askPermission: function () {
cordova.plugins.notification.local.requestPermission(showToast);
cordova.plugins.notification.local.requestPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
},
// Schedule a single notification
scheduleSingle: function () {
cordova.plugins.notification.local.schedule({
id: 1,
text: 'Test Message 1',
icon: 'http://3.bp.blogspot.com/-Qdsy-GpempY/UU_BN9LTqSI/AAAAAAAAAMA/LkwLW2yNBJ4/s1600/supersu.png',
smallIcon: 'res://cordova',
attachments: ['file://img/logo.png'],
sound: null,
badge: 1,
data: { test: 1 }
});
},
// Schedule multiple notifications at once
scheduleMultiple: function () {
cordova.plugins.notification.local.schedule([{
id: 1,
text: 'Multi Message 1',
icon: 'res://cordova'
}, {
id: 2,
text: 'Multi Message 2',
icon: 'res://icon',
smallIcon: 'ic_media_play'
}, {
id: 3,
text: 'Multi Message 3',
icon: 'res://icon',
smallIcon: 'ic_media_pause'
}]);
},
// Schedule a delayed notification
scheduleDelayed: function () {
var now = new Date().getTime(),
_5_sec_from_now = new Date(now + 5 * 1000);
var sound = device.platform == 'Android' ? 'file://sound.mp3' : 'file://beep.caf';
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Scheduled with delay',
text: 'Test Message 1',
at: _5_sec_from_now,
sound: sound,
badge: 12
});
},
// Schedule a repeating notification
scheduleInterval: function () {
var sound = device.platform == 'Android' ? 'file://sound.mp3' : 'file://beep.caf';
cordova.plugins.notification.local.schedule({
id: 1,
text: 'Scheduled every minute',
every: 'minute',
sound: sound,
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
},
// Clear a single notification
clearSingle: function () {
cordova.plugins.notification.local.clear(1, app.ids);
},
// Clear multiple notifications
clearMulti: function () {
cordova.plugins.notification.local.clear([2, 3], app.ids);
},
// Clear all notifications
clearAll: function () {
cordova.plugins.notification.local.clearAll(app.ids);
},
// Clear a single notification
cancelSingle: function () {
cordova.plugins.notification.local.cancel(1, app.ids);
},
// Clear multiple notifications
cancelMulti: function () {
cordova.plugins.notification.local.cancel([2, 3], app.ids);
},
// Cancel all notifications
cancelAll: function () {
cordova.plugins.notification.local.cancelAll(app.ids);
},
// If the notifcation is scheduled or triggered
isPresent: function () {
cordova.plugins.notification.local.isPresent(1, function (present) {
showToast(present ? 'Yes' : 'No');
});
},
// If the notifcation is scheduled
isScheduled: function () {
cordova.plugins.notification.local.isScheduled(1, function (scheduled) {
showToast(scheduled ? 'Yes' : 'No');
});
},
// If the notifcation is triggered
isTriggered: function () {
cordova.plugins.notification.local.isTriggered(1, function (triggered) {
showToast(triggered ? 'Yes' : 'No');
});
},
// Get all notification ids
ids: function () {
cordova.plugins.notification.local.getIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all notification ids
scheduledIds: function () {
cordova.plugins.notification.local.getScheduledIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all notification ids
triggeredIds: function () {
cordova.plugins.notification.local.getTriggeredIds(function (ids) {
console.log(ids);
showToast(ids.length === 0 ? '- none -' : ids.join(' ,'));
});
},
// Get all scheduled notifications
scheduledNots: function () {
cordova.plugins.notification.local.getAllScheduled(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get all triggered notifications
triggeredNots: function () {
cordova.plugins.notification.local.getAllTriggered(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get a single notification
notification: function () {
cordova.plugins.notification.local.get(1, function (obj) {
console.log(obj);
showToast(obj ? obj.toString() : '- none -');
});
},
// Get multiple notifications
multipleNots: function () {
cordova.plugins.notification.local.get([1, 2], function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Get all notifications
notifications: function () {
cordova.plugins.notification.local.getAll(function (nots) {
console.log(nots);
showToast(nots.length === 0 ? '- none -' : nots.join(' ,'));
});
},
// Set another default title
setDefaultTitle: function () {
cordova.plugins.notification.local.setDefaults({ title: 'New Default Title' });
showToast('New Default Title');
},
// Listen for events
bindNotificationEvents: function () {
cordova.plugins.notification.local.on('schedule', function (obj) {
console.log('onschedule', arguments);
// showToast('scheduled: ' + obj.id);
});
cordova.plugins.notification.local.on('update', function (obj) {
console.log('onupdate', arguments);
// showToast('updated: ' + obj.id);
});
cordova.plugins.notification.local.on('trigger', function (obj) {
console.log('ontrigger', arguments);
showToast('triggered: ' + obj.id);
});
cordova.plugins.notification.local.on('click', function (obj) {
console.log('onclick', arguments);
showToast('clicked: ' + obj.id);
});
cordova.plugins.notification.local.on('cancel', function (obj) {
console.log('oncancel', arguments);
// showToast('canceled: ' + obj.id);
});
cordova.plugins.notification.local.on('clear', function (obj) {
console.log('onclear', arguments);
showToast('cleared: ' + obj.id);
});
cordova.plugins.notification.local.on('cancelall', function () {
console.log('oncancelall', arguments);
// showToast('canceled all');
});
cordova.plugins.notification.local.on('clearall', function () {
console.log('onclearall', arguments);
// showToast('cleared all');
});
}
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment