Commit 008a0ec0 by Sebastián Katzer

Update to latest work in progress

parent 58f57589
...@@ -18,8 +18,12 @@ ...@@ -18,8 +18,12 @@
D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E4042BD923824AEB9E9079DC /* QuartzCore.framework */; }; D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E4042BD923824AEB9E9079DC /* QuartzCore.framework */; };
E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = B49413F707024AE39907B73F /* libz.tbd */; }; E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = B49413F707024AE39907B73F /* libz.tbd */; };
E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A150CBE2B3E47C5A4319096 /* CDVDevice.m */; }; E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 8A150CBE2B3E47C5A4319096 /* CDVDevice.m */; };
97FC38A49B614F60924CA868 /* APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = AAE54FB53C834C988F009E8E /* APPLocalNotification.m */; }; 26FD3FAAFA0747BC88376EE2 /* APPLocalNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = 57C74515BDFF4954B31FA9FE /* APPLocalNotification.m */; };
F89024F36A5F47C2B8531ACA /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4834642E539E4FB8A4B714D9 /* UserNotifications.framework */; }; 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 */ /* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */ /* Begin PBXContainerItemProxy section */
...@@ -75,9 +79,17 @@ ...@@ -75,9 +79,17 @@
EB87FDF41871DAF40020F90C /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = ../../config.xml; sourceTree = "<group>"; }; 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>"; }; 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>"; }; 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; }; 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; };
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; }; 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; };
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; }; 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 */ /* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
...@@ -88,7 +100,7 @@ ...@@ -88,7 +100,7 @@
301BF552109A68D80062928A /* libCordova.a in Frameworks */, 301BF552109A68D80062928A /* libCordova.a in Frameworks */,
E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */, E09211A0D1294D6588191EB4 /* libz.tbd in Frameworks */,
D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */, D0D06B90644D41EAAE8C16D6 /* QuartzCore.framework in Frameworks */,
F89024F36A5F47C2B8531ACA /* UserNotifications.framework in Frameworks */, 4B56A07F7C6F40C08671CF74 /* UserNotifications.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
...@@ -161,7 +173,7 @@ ...@@ -161,7 +173,7 @@
children = ( children = (
B49413F707024AE39907B73F /* libz.tbd */, B49413F707024AE39907B73F /* libz.tbd */,
E4042BD923824AEB9E9079DC /* QuartzCore.framework */, E4042BD923824AEB9E9079DC /* QuartzCore.framework */,
4834642E539E4FB8A4B714D9 /* UserNotifications.framework */, 010B54B769874E79994B98E0 /* UserNotifications.framework */,
); );
name = Frameworks; name = Frameworks;
sourceTree = "<group>"; sourceTree = "<group>";
...@@ -194,8 +206,16 @@ ...@@ -194,8 +206,16 @@
816F86ACE6CD4C8E8FA7A84A /* Toast.m */, 816F86ACE6CD4C8E8FA7A84A /* Toast.m */,
A380129C71E248EDBC5BE744 /* Toast+UIView.h */, A380129C71E248EDBC5BE744 /* Toast+UIView.h */,
84764C161F33453AB5FD1235 /* Toast.h */, 84764C161F33453AB5FD1235 /* Toast.h */,
AAE54FB53C834C988F009E8E /* APPLocalNotification.m */, 57C74515BDFF4954B31FA9FE /* APPLocalNotification.m */,
99F477B096B14D80BDA21DAB /* APPLocalNotification.h */, 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; name = Plugins;
path = NotificationExample/Plugins; path = NotificationExample/Plugins;
...@@ -239,6 +259,11 @@ ...@@ -239,6 +259,11 @@
isa = PBXProject; isa = PBXProject;
attributes = { attributes = {
LastUpgradeCheck = 830; LastUpgradeCheck = 830;
TargetAttributes = {
1D6058900D05DD3D006BFB54 = {
DevelopmentTeam = V3FHQ5C4T6;
};
};
}; };
buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "NotificationExample" */; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "NotificationExample" */;
compatibilityVersion = "Xcode 3.2"; compatibilityVersion = "Xcode 3.2";
...@@ -321,7 +346,11 @@ ...@@ -321,7 +346,11 @@
E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */, E27F123D4ACE4BF39165B055 /* CDVDevice.m in Sources */,
CA605C2FE84D46FC94CE18B1 /* Toast+UIView.m in Sources */, CA605C2FE84D46FC94CE18B1 /* Toast+UIView.m in Sources */,
91E68846231A433A8F26E364 /* Toast.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; runOnlyForDeploymentPostprocessing = 0;
}; };
...@@ -346,6 +375,7 @@ ...@@ -346,6 +375,7 @@
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
DEVELOPMENT_TEAM = V3FHQ5C4T6;
GCC_DYNAMIC_NO_PIC = NO; GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0; GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
...@@ -371,6 +401,7 @@ ...@@ -371,6 +401,7 @@
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = YES; COPY_PHASE_STRIP = YES;
DEVELOPMENT_TEAM = V3FHQ5C4T6;
GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "NotificationExample/NotificationExample-Prefix.pch"; GCC_PREFIX_HEADER = "NotificationExample/NotificationExample-Prefix.pch";
GCC_THUMB_SUPPORT = NO; GCC_THUMB_SUPPORT = NO;
......
...@@ -2,121 +2,141 @@ ...@@ -2,121 +2,141 @@
"images" : [ "images" : [
{ {
"idiom" : "iphone", "idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"size" : "29x29", "size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small.png", "filename" : "icon-small.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "iphone",
"size" : "29x29", "size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small@2x.png", "filename" : "icon-small@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "iphone",
"size" : "29x29", "size" : "29x29",
"idiom" : "iphone",
"filename" : "icon-small@3x.png", "filename" : "icon-small@3x.png",
"scale" : "3x" "scale" : "3x"
}, },
{ {
"idiom" : "iphone",
"size" : "40x40", "size" : "40x40",
"idiom" : "iphone",
"filename" : "icon-40@2x.png", "filename" : "icon-40@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "iphone",
"size" : "40x40", "size" : "40x40",
"idiom" : "iphone",
"filename" : "icon-60@2x.png", "filename" : "icon-60@2x.png",
"scale" : "3x" "scale" : "3x"
}, },
{ {
"idiom" : "iphone",
"size" : "57x57", "size" : "57x57",
"idiom" : "iphone",
"filename" : "icon.png", "filename" : "icon.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "iphone",
"size" : "57x57", "size" : "57x57",
"idiom" : "iphone",
"filename" : "icon@2x.png", "filename" : "icon@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "iphone",
"size" : "60x60", "size" : "60x60",
"idiom" : "iphone",
"filename" : "icon-60@2x.png", "filename" : "icon-60@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "iphone",
"size" : "60x60", "size" : "60x60",
"idiom" : "iphone",
"filename" : "icon-60@3x.png", "filename" : "icon-60@3x.png",
"scale" : "3x" "scale" : "3x"
}, },
{ {
"idiom" : "ipad", "idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"size" : "29x29", "size" : "29x29",
"idiom" : "ipad",
"filename" : "icon-small.png", "filename" : "icon-small.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "ipad",
"size" : "29x29", "size" : "29x29",
"idiom" : "ipad",
"filename" : "icon-small@2x.png", "filename" : "icon-small@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "ipad",
"size" : "40x40", "size" : "40x40",
"idiom" : "ipad",
"filename" : "icon-40.png", "filename" : "icon-40.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "ipad",
"size" : "40x40", "size" : "40x40",
"idiom" : "ipad",
"filename" : "icon-40@2x.png", "filename" : "icon-40@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "ipad",
"size" : "50x50", "size" : "50x50",
"idiom" : "ipad",
"filename" : "icon-50.png", "filename" : "icon-50.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "ipad",
"size" : "50x50", "size" : "50x50",
"idiom" : "ipad",
"filename" : "icon-50@2x.png", "filename" : "icon-50@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "ipad",
"size" : "72x72", "size" : "72x72",
"idiom" : "ipad",
"filename" : "icon-72.png", "filename" : "icon-72.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "ipad",
"size" : "72x72", "size" : "72x72",
"idiom" : "ipad",
"filename" : "icon-72@2x.png", "filename" : "icon-72@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "ipad",
"size" : "76x76", "size" : "76x76",
"idiom" : "ipad",
"filename" : "icon-76.png", "filename" : "icon-76.png",
"scale" : "1x" "scale" : "1x"
}, },
{ {
"idiom" : "ipad",
"size" : "76x76", "size" : "76x76",
"idiom" : "ipad",
"filename" : "icon-76@2x.png", "filename" : "icon-76@2x.png",
"scale" : "2x" "scale" : "2x"
}, },
{ {
"idiom" : "ipad",
"size" : "83.5x83.5", "size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon-83.5@2x.png", "filename" : "icon-83.5@2x.png",
"scale" : "2x" "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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * Version 2.0 (the 'License'). You may not use this file except in
...@@ -13,6 +17,8 @@ ...@@ -13,6 +17,8 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
#import <Cordova/CDVPlugin.h> #import <Cordova/CDVPlugin.h>
...@@ -29,45 +35,45 @@ ...@@ -29,45 +35,45 @@
// Request permission to show notifications // Request permission to show notifications
- (void) request:(CDVInvokedUrlCommand*)command; - (void) request:(CDVInvokedUrlCommand*)command;
//// Schedule set of notifications // Schedule notifications
//- (void) schedule:(CDVInvokedUrlCommand*)command; - (void) schedule:(CDVInvokedUrlCommand*)command;
//// Update set of notifications //// Update set of notifications
//- (void) update:(CDVInvokedUrlCommand*)command; //- (void) update:(CDVInvokedUrlCommand*)command;
//// Cancel set of notifications // Clear notifications by id
//- (void) cancel:(CDVInvokedUrlCommand*)command; - (void) clear:(CDVInvokedUrlCommand*)command;
//// Cancel all notifications // Clear all notifications
//- (void) cancelAll:(CDVInvokedUrlCommand*)command; - (void) clearAll:(CDVInvokedUrlCommand*)command;
//// Clear set of notifications // Cancel notifications by id
//- (void) clear:(CDVInvokedUrlCommand*)command; - (void) cancel:(CDVInvokedUrlCommand*)command;
//// Clear all notifications // Cancel all notifications
//- (void) clearAll:(CDVInvokedUrlCommand*)command; - (void) cancelAll:(CDVInvokedUrlCommand*)command;
//
//// If a notification with an ID is present // If a notification with an ID is present
//- (void) isPresent:(CDVInvokedUrlCommand*)command; - (void) isPresent:(CDVInvokedUrlCommand*)command;
//// If a notification with an ID is scheduled // If a notification with an ID is scheduled
//- (void) isScheduled:(CDVInvokedUrlCommand*)command; - (void) isScheduled:(CDVInvokedUrlCommand*)command;
//// If a notification with an ID is triggered // If a notification with an ID is triggered
//- (void) isTriggered:(CDVInvokedUrlCommand*)command; - (void) isTriggered:(CDVInvokedUrlCommand*)command;
//
//// List all ids from all local notifications // List of all notification IDs
//- (void) getAllIds:(CDVInvokedUrlCommand*)command; - (void) ids:(CDVInvokedUrlCommand*)command;
//// List all ids from all pending notifications // List of all scheduled notification IDs
//- (void) getScheduledIds:(CDVInvokedUrlCommand*)command; - (void) scheduledIds:(CDVInvokedUrlCommand*)command;
//// List all ids from all triggered notifications // List of all triggered notification IDs
//- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command; - (void) triggeredIds:(CDVInvokedUrlCommand*)command;
//
//// Propertys for given local notification // Notification by id
//- (void) getSingle:(CDVInvokedUrlCommand*)command; - (void) notification:(CDVInvokedUrlCommand*)command;
//// Propertya for given scheduled notification // Scheduled notification by id
//- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command; - (void) scheduledNotification:(CDVInvokedUrlCommand*)command;
//// Propertys for given triggered notification // Triggered notification by id
//- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command; - (void) triggeredNotification:(CDVInvokedUrlCommand*)command;
//
//// Property list for given local notifications // List of notifications by id
//- (void) getAll:(CDVInvokedUrlCommand*)command; - (void) notifications:(CDVInvokedUrlCommand*)command;
//// Property list for given scheduled notifications // List of scheduled notifications by id
//- (void) getScheduled:(CDVInvokedUrlCommand*)command; - (void) scheduledNotifications:(CDVInvokedUrlCommand*)command;
//// Property list for given triggered notifications // List of triggered notifications by id
//- (void) getTriggered:(CDVInvokedUrlCommand*)command; - (void) triggeredNotifications:(CDVInvokedUrlCommand*)command;
@end @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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * Version 2.0 (the 'License'). You may not use this file except in
...@@ -13,28 +17,23 @@ ...@@ -13,28 +17,23 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "APPLocalNotification.h" #import "APPLocalNotification.h"
//#import "APPLocalNotificationOptions.h" #import "APPNotificationOptions.h"
//#import "UNUserNotificationCenter+APPLocalNotification.h" #import "UNUserNotificationCenter+APPLocalNotification.h"
//#import "UNNotificationRequest+APPLocalNotification.h" #import "UNNotificationRequest+APPLocalNotification.h"
//#import "UNMutableNotificationContent+APPLocalNotification.h" #import "APPNotificationContent.h"
@interface APPLocalNotification () @interface APPLocalNotification ()
// Property reader for [self app] @property (strong, nonatomic) UIApplication* app;
@property (readonly, getter=app) UIApplication* app; @property (strong, nonatomic) UNUserNotificationCenter* center;
// Property reader for [self center]
@property (readonly, getter=center) UNUserNotificationCenter* center;
// All events will be queued until deviceready has been fired
@property (readwrite, assign) BOOL deviceready; @property (readwrite, assign) BOOL deviceready;
// Event queue
@property (readonly, nonatomic, retain) NSMutableArray* eventQueue; @property (readonly, nonatomic, retain) NSMutableArray* eventQueue;
// IOS9: TODO remove later
@property (nonatomic, retain) CDVInvokedUrlCommand* command;
@end @end
@implementation APPLocalNotification @implementation APPLocalNotification
...@@ -46,6 +45,8 @@ ...@@ -46,6 +45,8 @@
/** /**
* Execute all queued events. * Execute all queued events.
*
* @return [ Void ]
*/ */
- (void) deviceready:(CDVInvokedUrlCommand*)command - (void) deviceready:(CDVInvokedUrlCommand*)command
{ {
...@@ -57,48 +58,32 @@ ...@@ -57,48 +58,32 @@
[eventQueue removeAllObjects]; [eventQueue removeAllObjects];
} }
//
///** /**
// * Schedule a set of notifications. * Schedule notifications.
// * *
// * @param properties * @param [Array<Hash>] properties A list of key-value properties.
// * A dict of properties for each notification *
// */ * @return [ Void ]
//- (void) schedule:(CDVInvokedUrlCommand*)command */
//{ - (void) schedule:(CDVInvokedUrlCommand*)command
// NSArray* notifications = command.arguments; {
// NSArray* notifications = command.arguments;
// [self.commandDelegate runInBackground:^{
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { [self.commandDelegate runInBackground:^{
// for (NSDictionary* options in notifications) { for (NSDictionary* options in notifications) {
// UNMutableNotificationContent* notification; APPNotificationContent* notification;
//
// notification = [[UNMutableNotificationContent alloc] notification = [[APPNotificationContent alloc]
// initWithOptions:options]; initWithOptions:options];
//
// [self scheduleNotification:notification]; [self scheduleNotification:notification];
// //[self fireEvent:@"add" notification:notification]; }
// }
// } else { [self execCallback:command];
// 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. // * Update a set of notifications.
// * // *
...@@ -153,391 +138,350 @@ ...@@ -153,391 +138,350 @@
// [self execCallback:command]; // [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];
// }];
//}
/** /**
* Check for permission to show notifications. * 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 - (void) check:(CDVInvokedUrlCommand*)command
{ {
[self.center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) { [_center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized; BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized;
BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled; BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled;
BOOL permitted = authorized && enabled; BOOL permitted = authorized && enabled;
CDVPluginResult* result; CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsBool:permitted]; messageAsBool:permitted];
[self.commandDelegate sendPluginResult:result [self.commandDelegate sendPluginResult:result
callbackId:command.callbackId]; callbackId:command.callbackId];
}]; }];
...@@ -545,6 +489,8 @@ ...@@ -545,6 +489,8 @@
/** /**
* Request for permission to show notifcations. * Request for permission to show notifcations.
*
* @return [ Void ]
*/ */
- (void) request:(CDVInvokedUrlCommand*)command - (void) request:(CDVInvokedUrlCommand*)command
{ {
...@@ -557,25 +503,28 @@ ...@@ -557,25 +503,28 @@
} }
#pragma mark - #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. // * Update the local notification.
// */ // */
//- (void) updateNotification:(UILocalNotification*)notification //- (void) updateNotification:(UILocalNotification*)notification
// withOptions:(NSDictionary*)newOptions // withOptions:(NSDictionary*)newOptions
//{ //{APPNotificationRequest*
// NSMutableDictionary* options = [notification.userInfo mutableCopy]; // NSMutableDictionary* options = [notification.userInfo mutableCopy];
// //
// [options addEntriesFromDictionary:newOptions]; // [options addEntriesFromDictionary:newOptions];
...@@ -586,72 +535,44 @@ ...@@ -586,72 +535,44 @@
//// ////
//// [self scheduleLocalNotification:notification]; //// [self scheduleLocalNotification:notification];
//} //}
//
///** #pragma mark -
// * Cancel all local notifications. #pragma mark UNUserNotificationCenterDelegate
// */
//- (void) cancelAllNotifications /**
//{ * Called when a notification is delivered to the app while being in foreground.
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { */
// [self.center cancelAllNotifications]; - (void) userNotificationCenter:(UNUserNotificationCenter *)center
// } else { willPresentNotification:(UNNotification *)notification
// [self.app cancelAllLocalNotifications]; withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
// } {
// [self fireEvent:@"trigger" notification:notification.request];
// [self.app setApplicationIconBadgeNumber:0]; completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
//} }
//
///** /**
// * Clear all local notifications. * Called to let your app know which action was selected by the user for a given
// */ * notification.
//- (void) clearAllNotifications */
//{ - (void) userNotificationCenter:(UNUserNotificationCenter *)center
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { didReceiveNotificationResponse:(UNNotificationResponse *)response
// [self.center clearAllNotifications]; withCompletionHandler:(void (^)())completionHandler
// } else { {
// [self.app clearAllLocalNotifications]; UNNotificationRequest* notification = response.notification.request;
// } NSString* action = response.actionIdentifier;
// NSString* event = action;
// [self.app setApplicationIconBadgeNumber:0];
//} if ([action isEqualToString:UNNotificationDefaultActionIdentifier]) {
// event = @"click";
//#pragma mark - } else
//#pragma mark Delegates if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
// event = @"clear";
///** }
// * Called when a notification is delivered to a foreground app.
// */ [self fireEvent:event notification:notification];
//- (void) userNotificationCenter:(UNUserNotificationCenter *)center
// willPresentNotification:(UNNotification *)notification completionHandler();
// 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 -
#pragma mark Life Cycle #pragma mark Life Cycle
...@@ -662,249 +583,83 @@ ...@@ -662,249 +583,83 @@
- (void) pluginInitialize - (void) pluginInitialize
{ {
eventQueue = [[NSMutableArray alloc] init]; eventQueue = [[NSMutableArray alloc] init];
_app = [UIApplication sharedApplication];
_center = [UNUserNotificationCenter currentNotificationCenter];
self.center.delegate = self; _center.delegate = self;
[_center registerGeneralNotificationCategory];
} }
#pragma mark - #pragma mark -
#pragma mark Helper #pragma mark Helper
///** /**
// * Retrieves the application state * Retrieve the state of the application.
// * *
// * @return * @return "background" or "foreground"
// * Either "background" or "foreground" */
// */ - (NSString*) applicationState
//- (NSString*) applicationState {
//{ UIApplicationState state = [_app applicationState];
// UIApplicationState state = [self.app applicationState];
// bool isActive = state == UIApplicationStateActive;
// bool isActive = state == UIApplicationStateActive;
// return isActive ? @"foreground" : @"background";
// 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];
//}
/** /**
* 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. * Fire general event.
// */ *
//- (void) fireEvent:(NSString*)event * @param [ NSString* ] event The name of the event to fire.
//{ *
// [self fireEvent:event notification:NULL]; * @return [ Void ]
//} */
// - (void) fireEvent:(NSString*)event
///** {
// * Fire event for local notification. [self fireEvent:event notification:NULL];
// */ }
//- (void) fireEvent:(NSString*)event
// notification:(UNNotificationRequest*)notification /**
//{ * Fire event for about a local notification.
// NSString* js; *
// NSString* appState = [self applicationState]; * @param [ NSString* ] event The name of the event to fire.
// NSString* params = [NSString stringWithFormat:@"\"%@\"", appState]; * @param [ APPNotificationRequest* ] notification The local notification.
// *
// if (notification) { * @return [ Void ]
// NSString* args = [notification encodeToJSON]; */
// params = [NSString stringWithFormat:@"%@,'%@'", args, appState]; - (void) fireEvent:(NSString*)event
// } notification:(UNNotificationRequest*)request
// {
// js = [NSString stringWithFormat: NSString* js;
// @"cordova.plugins.notification.local.core.fireEvent('%@', %@)", NSString* appState = [self applicationState];
// event, params]; NSString* params = [NSString stringWithFormat:@"\"%@\"", appState];
//
// if (deviceready) { if (request) {
// [self.commandDelegate evalJs:js]; NSString* args = [request encodeToJSON];
// } else { params = [NSString stringWithFormat:@"%@,'%@'", args, appState];
// [self.eventQueue addObject:js]; }
// }
//} js = [NSString stringWithFormat:
// @"cordova.plugins.notification.local.core.fireEvent('%@', %@)",
//#pragma mark - event, params];
//#pragma mark ios 9
// if (deviceready) {
///** [self.commandDelegate evalJs:js];
// * Schedule the local notification. } else {
// */ [self.eventQueue addObject:js];
//- (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 @end
...@@ -21,27 +21,14 @@ ...@@ -21,27 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import <UserNotifications/UNNotificationSound.h> #import "APPNotificationOptions.h"
#import <UserNotifications/UNNotificationRequest.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface APPLocalNotificationOptions : NSObject @import UserNotifications;
- (id) initWithDict:(NSDictionary*)dict; @interface APPNotificationContent : UNMutableNotificationContent
@property (readonly, getter=id) NSNumber* id; - (id) initWithOptions:(NSDictionary*)dict;
@property (readonly, getter=identifier) NSString* identifier; - (APPNotificationOptions*) options;
@property (readonly, getter=title) NSString* title; - (UNNotificationRequest*) request;
@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;
@end @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 @@ ...@@ -21,43 +21,21 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "UILocalNotification+APPLocalNotification.ios9.h" @import UserNotifications;
@interface UIApplication (APPLocalNotification) @interface APPNotificationOptions : NSObject
@property (readonly, getter=localNotifications) NSArray* localNotifications; @property (readonly, getter=id) NSNumber* id;
@property (readonly, getter=localNotificationIds) NSArray* localNotificationIds; @property (readonly, getter=identifier) NSString* identifier;
@property (readonly, getter=title) NSString* title;
// If the app has the permission to schedule local notifications @property (readonly, getter=subtitle) NSString* subtitle;
- (BOOL) hasPermissionToScheduleLocalNotifications; @property (readonly, getter=badge) NSNumber* badge;
// Ask for permission to schedule local notifications @property (readonly, getter=text) NSString* text;
- (void) registerPermissionToScheduleLocalNotifications; @property (readonly, getter=sound) UNNotificationSound* sound;
@property (readonly, getter=attachments) NSArray<UNNotificationAttachment *> * attachments;
// List of all local notification IDs from given type @property (readonly, getter=userInfo) NSDictionary* userInfo;
- (NSArray*) localNotificationIdsByType:(APPNotificationType)type;
- (id) initWithDict:(NSDictionary*)dict;
// If local notification with ID exists - (UNNotificationTrigger*) trigger;
- (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;
@end @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 @@ ...@@ -21,18 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "APPLocalNotificationOptions.h" #import "APPNotificationOptions.h"
@import UserNotifications; @import UserNotifications;
@interface UNMutableNotificationContent (APPLocalNotification) @interface UNNotificationRequest (APPLocalNotification)
// Initialize a new local notification
- (id) initWithOptions:(NSDictionary*)dict;
// The options provided by the plug-in // The options provided by the plug-in
- (APPLocalNotificationOptions*) options; - (APPNotificationOptions*) options;
// Fully configured request to add the notification to the notification center
- (UNNotificationRequest*) request;
// Encode the user info dict to JSON // Encode the user info dict to JSON
- (NSString*) encodeToJSON; - (NSString*) encodeToJSON;
......
...@@ -21,62 +21,44 @@ ...@@ -21,62 +21,44 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "UNMutableNotificationContent+APPLocalNotification.h" #import "APPNotificationOptions.h"
#import "APPLocalNotificationOptions.h" #import "UNNotificationRequest+APPLocalNotification.h"
#import "APPNotificationContent.h"
#import <objc/runtime.h> #import <objc/runtime.h>
@import UserNotifications; @import UserNotifications;
static char optionsKey; static char optionsKey;
@implementation UNMutableNotificationContent (APPLocalNotification) @implementation UNNotificationRequest (APPLocalNotification)
#pragma mark -
#pragma mark Init
/** /**
* Initialize a local notification with the given options when calling on JS side: * Get associated option object
* notification.local.add(options)
*/ */
- (id) initWithOptions:(NSDictionary*)dict - (APPNotificationOptions*) getOptions
{ {
self = [self init]; return objc_getAssociatedObject(self, &optionsKey);
[self setUserInfo:dict];
[self __init];
return self;
} }
/** /**
* Applies the given options when calling on JS side: * Set associated option object
* notification.local.add(options)
*/ */
- (void) __init - (void) setOptions:(APPNotificationOptions*)options
{ {
APPLocalNotificationOptions* options = self.options; objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.title = options.title;
self.subtitle = options.subtitle;
self.body = options.text;
self.sound = options.sound;
self.badge = options.badge;
} }
#pragma mark -
#pragma mark Methods
/** /**
* The options provided by the plug-in. * The options provided by the plug-in.
*/ */
- (APPLocalNotificationOptions*) options - (APPNotificationOptions*) options
{ {
APPLocalNotificationOptions* options = [self getOptions]; APPNotificationOptions* options = [self getOptions];
if (!options) { if (!options) {
options = [[APPLocalNotificationOptions alloc] options = [[APPNotificationOptions alloc]
initWithDict:[self userInfo]]; initWithDict:[self.content userInfo]];
[self setOptions:options]; [self setOptions:options];
} }
...@@ -85,43 +67,13 @@ static char optionsKey; ...@@ -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. * Encode the user info dict to JSON.
*/ */
- (NSString*) encodeToJSON - (NSString*) encodeToJSON
{ {
NSString* json; NSString* json;
NSData* data; NSData* data;
NSMutableDictionary* obj = [self.userInfo mutableCopy]; NSMutableDictionary* obj = [self.content.userInfo mutableCopy];
[obj removeObjectForKey:@"updatedAt"]; [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) { 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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * 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 ...@@ -18,56 +14,60 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Core", func
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
var exec = require('cordova/exec'); 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 () { exports.hasPermission = function (callback, scope) {
return this._defaults; 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) { exports.requestPermission = function (callback, scope) {
var defaults = this.getDefaults(); var fn = this.createCallbackFn(callback, scope);
for (var key in defaults) { if (device.platform != 'iOS') {
if (newDefaults.hasOwnProperty(key)) { fn(true);
defaults[key] = newDefaults[key]; return;
}
} }
exec(fn, null, 'LocalNotification', 'request', []);
}; };
/** /**
* Schedule a new local notification. * Schedule notifications.
* *
* @param {Object} msgs * @param [ Array ] notifications The notifications to schedule.
* The notification properties * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been canceled * @param [ Object ] args Optional flags how to schedule.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/ */
exports.schedule = function (msgs, callback, scope, args) { exports.schedule = function (msgs, callback, scope, args) {
var fn = function(granted) { var fn = function (granted) {
if (!granted) return; if (!granted) return;
...@@ -86,55 +86,54 @@ exports.schedule = function (msgs, callback, scope, args) { ...@@ -86,55 +86,54 @@ exports.schedule = function (msgs, callback, scope, args) {
if (args && args.skipPermission) { if (args && args.skipPermission) {
fn.call(this, true); fn.call(this, true);
} else { } else {
this.registerPermission(fn, this); this.requestPermission(fn, this);
} }
}; };
/** // /**
* Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
* // *
* @param {Object} notifications // * @param {Object} notifications
* The notification properties to update // * The notification properties to update
* @param {Function} callback // * @param {Function} callback
* A function to be called after the notification has been updated // * A function to be called after the notification has been updated
* @param {Object?} scope // * @param {Object?} scope
* The scope for the callback function // * The scope for the callback function
* @param {Object?} args // * @param {Object?} args
* skipPermission:true schedules the notifications immediatly without // * skipPermission:true schedules the notifications immediatly without
* registering or checking for permission // * registering or checking for permission
*/ // */
exports.update = function (msgs, callback, scope, args) { // exports.update = function (msgs, callback, scope, args) {
var fn = function(granted) { // 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++) { // for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i]; // var notification = notifications[i];
this.convertProperties(notification); // this.convertProperties(notification);
} // }
this.exec('update', notifications, callback, scope); // this.exec('update', notifications, callback, scope);
}; // };
if (args && args.skipPermission) { // if (args && args.skipPermission) {
fn.call(this, true); // fn.call(this, true);
} else { // } else {
this.registerPermission(fn, this); // this.registerPermission(fn, this);
} // }
}; // };
/** /**
* Clear the specified notification. * Clear the specified notifications by id.
* *
* @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been cleared *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.clear = function (ids, callback, scope) { exports.clear = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids]; ids = Array.isArray(ids) ? ids : [ids];
...@@ -144,26 +143,25 @@ exports.clear = function (ids, callback, scope) { ...@@ -144,26 +143,25 @@ exports.clear = function (ids, callback, scope) {
}; };
/** /**
* Clear all previously sheduled notifications. * Clear all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
this.exec('clearAll', null, callback, scope); this.exec('clearAll', null, callback, scope);
}; };
/** /**
* Cancel the specified notifications. * Clear the specified notifications by id.
* *
* @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notifications has been canceled *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.cancel = function (ids, callback, scope) { exports.cancel = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids]; ids = Array.isArray(ids) ? ids : [ids];
...@@ -173,69 +171,66 @@ exports.cancel = function (ids, callback, scope) { ...@@ -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 * @return [ Void ]
* 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) { exports.cancelAll = function (callback, scope) {
this.exec('cancelAll', null, callback, scope); this.exec('cancelAll', null, callback, scope);
}; };
/** /**
* Check if a notification with an ID is present. * Check if a notification is present.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isPresent = function (id, callback, scope) { 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. * Check if a notification is scheduled.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isScheduled = function (id, callback, scope) { 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. * Check if a notification was triggered.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isTriggered = function (id, callback, scope) { 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 The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* *
* @param {Function} callback * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllIds = function (callback, scope) { exports.getAllIds = function (callback, scope) {
this.exec('getAllIds', null, callback, scope); this.exec('ids', null, callback, scope);
}; };
/** /**
...@@ -246,39 +241,38 @@ exports.getIds = function () { ...@@ -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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getScheduledIds = function (callback, scope) { 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getTriggeredIds = function (callback, scope) { 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.get = function () { exports.get = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -292,37 +286,36 @@ exports.get = function () { ...@@ -292,37 +286,36 @@ exports.get = function () {
scope = args[2]; scope = args[2];
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingle', Number(ids), callback, scope); this.exec('notification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getAll = function (callback, scope) { 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getScheduled = function () { exports.getScheduled = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -340,37 +333,34 @@ exports.getScheduled = function () { ...@@ -340,37 +333,34 @@ exports.getScheduled = function () {
} }
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingleScheduled', Number(ids), callback, scope); this.exec('scheduledNotification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllScheduled = function (callback, 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getTriggered = function () { exports.getTriggered = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -388,86 +378,59 @@ exports.getTriggered = function () { ...@@ -388,86 +378,59 @@ exports.getTriggered = function () {
} }
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingleTriggered', Number(ids), callback, scope); this.exec('triggeredNotification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllTriggered = function (callback, 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 * @return [ Object ]
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
*/ */
exports.hasPermission = function (callback, scope) { exports.getDefaults = function () {
var fn = this.createCallbackFn(callback, scope); return this._defaults;
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
}; };
/** /**
* Register permission to show notifications if not already granted. * Overwrite default settings.
* *
* @param {Function} callback * @param [ Object ] newDefaults New default values.
* The function to be exec as the callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
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;
}
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') { for (var key in defaults) {
fn(true); if (newDefaults.hasOwnProperty(key)) {
return; defaults[key] = newDefaults[key];
}
} }
exec(fn, null, 'LocalNotification', 'request', []);
}; };
/**********
* EVENTS *
**********/
/** /**
* Register callback for given event. * Register callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* The function to be exec as callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
exports.on = function (event, callback, scope) { exports.on = function (event, callback, scope) {
...@@ -486,10 +449,10 @@ exports.on = function (event, callback, scope) { ...@@ -486,10 +449,10 @@ exports.on = function (event, callback, scope) {
/** /**
* Unregister callback for given event. * Unregister callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback *
* The function to be exec as callback * @return [ Void ]
*/ */
exports.un = function (event, callback) { exports.un = function (event, callback) {
var listener = this._listener[event]; var listener = this._listener[event];
......
cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", function(require, exports, module) { 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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * 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 ...@@ -18,18 +14,11 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", func
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
var exec = require('cordova/exec'), var exec = require('cordova/exec'),
channel = require('cordova/channel'); channel = require('cordova/channel');
/***********
* MEMBERS *
***********/
// Default values // Default values
exports._defaults = { exports._defaults = {
text: '', text: '',
...@@ -42,48 +31,38 @@ exports._defaults = { ...@@ -42,48 +31,38 @@ exports._defaults = {
at: undefined at: undefined
}; };
// listener // Listener
exports._listener = {}; exports._listener = {};
// Registered permission flag
exports._registered = false;
/********
* UTIL *
********/
/** /**
* Merge platform specific properties into the default ones. * Merge platform specific properties into the default ones.
* *
* @return {Object} * @return [ Void ]
* The default properties for the platform
*/ */
exports.applyPlatformSpecificOptions = function () { exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults; var defaults = this._defaults;
switch (device.platform) { switch (device.platform) {
case 'Android': case 'Android':
defaults.icon = 'res://ic_popup_reminder'; defaults.icon = 'res://ic_popup_reminder';
defaults.smallIcon = undefined; defaults.smallIcon = undefined;
defaults.ongoing = false; defaults.ongoing = false;
defaults.autoClear = true; defaults.autoClear = true;
defaults.led = undefined; defaults.led = undefined;
defaults.color = undefined; defaults.color = undefined;
break;
case 'iOS':
defaults.attachments = undefined;
break; break;
} }
return defaults;
}; };
/** /**
* Merge custom properties with the default values. * Merge custom properties with the default values.
* *
* @param {Object} options * @param [ Object ] options Set of custom values.
* Set of custom values
* *
* @retrun {Object} * @retrun [ Object ]
* The merged property list
*/ */
exports.mergeWithDefaults = function (options) { exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults(); var defaults = this.getDefaults();
...@@ -127,11 +106,9 @@ exports.mergeWithDefaults = function (options) { ...@@ -127,11 +106,9 @@ exports.mergeWithDefaults = function (options) {
/** /**
* Convert the passed values to their required type. * Convert the passed values to their required type.
* *
* @param {Object} options * @param [ Object ] options Properties to convert for.
* Set of custom values
* *
* @retrun {Object} * @return [ Object ] The converted property list
* The converted property list
*/ */
exports.convertProperties = function (options) { exports.convertProperties = function (options) {
...@@ -173,46 +150,33 @@ exports.convertProperties = function (options) { ...@@ -173,46 +150,33 @@ exports.convertProperties = function (options) {
options.data = JSON.stringify(options.data); 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; 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 * @param [ Function ] fn The function to be exec as the callback.
* The callback function * @param [ Object ] scope The callback function's scope.
* @param {Object} scope
* The scope for the function
* *
* @return {Function} * @return [ Function ]
* The new callback function
*/ */
exports.createCallbackFn = function (callbackFn, scope) { exports.createCallbackFn = function (fn, scope) {
if (typeof callbackFn != 'function') if (typeof fn != 'function')
return; return;
return function () { return function () {
callbackFn.apply(scope || this, arguments); fn.apply(scope || this, arguments);
}; };
}; };
/** /**
* Convert the IDs to numbers. * Convert the IDs to numbers.
* *
* @param {String/Number[]} ids * @param [ Array ] ids
* *
* @return Array of Numbers * @return [ Array<Number> ]
*/ */
exports.convertIds = function (ids) { exports.convertIds = function (ids) {
var convertedIds = []; var convertedIds = [];
...@@ -227,10 +191,10 @@ exports.convertIds = function (ids) { ...@@ -227,10 +191,10 @@ exports.convertIds = function (ids) {
/** /**
* First found value for the given keys. * First found value for the given keys.
* *
* @param {Object} options * @param [ Object ] options Object with key-value properties.
* Object with key-value properties * @param [ *Array<String> ] keys List of keys.
* @param {String[]} keys* *
* Key list * @return [ Object ]
*/ */
exports.getValueFor = function (options) { exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1); var keys = Array.apply(null, arguments).slice(1);
...@@ -245,12 +209,12 @@ exports.getValueFor = function (options) { ...@@ -245,12 +209,12 @@ exports.getValueFor = function (options) {
}; };
/** /**
* Fire event with given arguments. * Fire the event with given arguments.
* *
* @param {String} event * @param [ String ] event The event's name.
* The event's name * @param [ *Array] args The callback's arguments.
* @param {args*} *
* The callback's arguments * @return [ Void]
*/ */
exports.fireEvent = function (event) { exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1), var args = Array.apply(null, arguments).slice(1),
...@@ -270,14 +234,12 @@ exports.fireEvent = function (event) { ...@@ -270,14 +234,12 @@ exports.fireEvent = function (event) {
/** /**
* Execute the native counterpart. * Execute the native counterpart.
* *
* @param {String} action * @param [ String ] action The name of the action.
* The name of the action * @param [ Array ] args Array of arguments.
* @param args[] * @param [ Function] callback The callback function.
* Array of arguments * @param [ Object ] scope The scope for the function.
* @param {Function} callback *
* The callback function * @return [ Void ]
* @param {Object} scope
* The scope for the function
*/ */
exports.exec = function (action, args, callback, scope) { exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope), var fn = this.createCallbackFn(callback, scope),
...@@ -292,11 +254,6 @@ exports.exec = function (action, args, callback, scope) { ...@@ -292,11 +254,6 @@ exports.exec = function (action, args, callback, scope) {
exec(fn, null, 'LocalNotification', action, params); exec(fn, null, 'LocalNotification', action, params);
}; };
/*********
* HOOKS *
*********/
// Called after 'deviceready' event // Called after 'deviceready' event
channel.deviceready.subscribe(function () { channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered // Device is ready now, the listeners are registered
......
cordova.define("cordova-plugin-local-notifications.LocalNotification", function(require, exports, module) { 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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * 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( ...@@ -18,192 +14,159 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification", function(
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
/*************
* INTERFACE *
*************/
/** /**
* Returns the default settings. * Request permission to show notifications.
* *
* @return {Object} * @param [ Function ] callback The function to be exec as the callback.
*/ * @param [ Object ] scope The callback function's scope.
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 * @return [ Void ]
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
*/ */
exports.hasPermission = function (callback, scope) { exports.hasPermission = function (callback, scope) {
this.core.hasPermission(callback, scope); this.core.hasPermission(callback, scope);
}; };
/** /**
* Register permission to show notifications if not already granted. * Request permission to show notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* The function to be exec as the callback * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The callback function's scope * @return [ Void ]
*/ */
exports.requestPermission = function (callback, scope) { exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope); this.core.requestPermission(callback, scope);
}; };
/** /**
* Schedule a new local notification. * Schedule notifications.
* *
* @param {Object} notifications * @param [ Array ] notifications The notifications to schedule.
* The notification properties * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been canceled * @param [ Object ] args Optional flags how to schedule.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/ */
exports.schedule = function (notifications, callback, scope, args) { exports.schedule = function (notifications, callback, scope, args) {
this.core.schedule(notifications, callback, scope, args); this.core.schedule(notifications, callback, scope, args);
}; };
/** // /**
* Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
* // *
* @param {Object} notifications // * @param {Object} notifications
* The notification properties to update // * The notification properties to update
* @param {Function} callback // * @param {Function} callback
* A function to be called after the notification has been updated // * A function to be called after the notification has been updated
* @param {Object?} scope // * @param {Object?} scope
* The scope for the callback function // * The scope for the callback function
* @param {Object?} args // * @param {Object?} args
* skipPermission:true schedules the notifications immediatly without // * skipPermission:true schedules the notifications immediatly without
* registering or checking for permission // * registering or checking for permission
*/ // */
exports.update = function (notifications, callback, scope, args) { // exports.update = function (notifications, callback, scope, args) {
this.core.update(notifications, callback, scope, args); // this.core.update(notifications, callback, scope, args);
}; // };
/** /**
* Clear the specified notification. * Clear the specified notifications by id.
* *
* @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been cleared *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.clear = function (ids, callback, scope) { exports.clear = function (ids, callback, scope) {
this.core.clear(ids, callback, scope); this.core.clear(ids, callback, scope);
}; };
/** /**
* Clear all previously sheduled notifications. * Clear all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
this.core.clearAll(callback, scope); this.core.clearAll(callback, scope);
}; };
/** /**
* Cancel the specified notifications. * Cancel the specified notifications by id.
* *
* @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notifications has been canceled *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.cancel = function (ids, callback, scope) { exports.cancel = function (ids, callback, scope) {
this.core.cancel(ids, callback, scope); this.core.cancel(ids, callback, scope);
}; };
/** /**
* Remove all previously registered notifications. * Cancel all scheduled notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been canceled * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.cancelAll = function (callback, scope) { exports.cancelAll = function (callback, scope) {
this.core.cancelAll(callback, scope); this.core.cancelAll(callback, scope);
}; };
/** /**
* Check if a notification with an ID is present. * Check if a notification is present.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isPresent = function (id, callback, scope) { exports.isPresent = function (id, callback, scope) {
this.core.isPresent(id, callback, scope); this.core.isPresent(id, callback, scope);
}; };
/** /**
* Check if a notification with an ID is scheduled. * Check if a notification is scheduled.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isScheduled = function (id, callback, scope) { exports.isScheduled = function (id, callback, scope) {
this.core.isScheduled(id, callback, scope); this.core.isScheduled(id, callback, scope);
}; };
/** /**
* Check if a notification with an ID was triggered. * Check if a notification was triggered.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isTriggered = function (id, callback, scope) { exports.isTriggered = function (id, callback, scope) {
this.core.isTriggered(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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllIds = function (callback, scope) { exports.getAllIds = function (callback, scope) {
this.core.getAllIds(callback, scope); this.core.getAllIds(callback, scope);
...@@ -217,148 +180,131 @@ exports.getIds = function () { ...@@ -217,148 +180,131 @@ exports.getIds = function () {
}; };
/** /**
* List all scheduled notification IDs. * List of all scheduled notification IDs.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getScheduledIds = function (callback, scope) { exports.getScheduledIds = function (callback, scope) {
this.core.getScheduledIds(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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getTriggeredIds = function (callback, scope) { exports.getTriggeredIds = function (callback, scope) {
this.core.getTriggeredIds(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.get = function () { exports.get = function (ids, callback, scope) {
this.core.get.apply(this.core, arguments); 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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAll = function (callback, scope) { exports.getAll = function (callback, scope) {
this.core.getAll(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getScheduled = function () { exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled.apply(this.core, arguments); this.core.getScheduled(ids, callback, scope);
}; };
/** /**
* Property list for all scheduled notifications. * List of all scheduled notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllScheduled = function (callback, scope) { exports.getAllScheduled = function (callback, scope) {
this.core.getAllScheduled(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getTriggered = function () { exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered.apply(this.core, arguments); this.core.getTriggered(ids, callback, scope);
}; };
/** /**
* Property list for all triggered notifications. * List of all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllTriggered = function (callback, scope) { exports.getAllTriggered = function (callback, scope) {
this.core.getAllTriggered(callback, scope); this.core.getAllTriggered(callback, scope);
}; };
/****************
* DEPRECATIONS *
****************/
/** /**
* Schedule a new local notification. * The (platform specific) default settings.
*
* @return [ Object ]
*/ */
exports.add = function () { exports.getDefaults = function () {
console.warn('Depreated: Please use `notification.local.schedule` instead.'); return this.core.getDefaults();
this.schedule.apply(this, arguments);
}; };
/** /**
* Register permission to show notifications * Overwrite default settings.
* if not already granted. *
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/ */
exports.promptForPermission = function () { exports.setDefaults = function (defaults) {
console.warn('Depreated: Please use `notification.local.registerPermission` instead.'); this.core.setDefaults(defaults);
this.registerPermission.apply(this, arguments);
}; };
/**********
* EVENTS *
**********/
/** /**
* Register callback for given event. * Register callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* The function to be exec as callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
exports.on = function (event, callback, scope) { exports.on = function (event, callback, scope) {
this.core.on(event, callback, scope); this.core.on(event, callback, scope);
...@@ -367,10 +313,10 @@ exports.on = function (event, callback, scope) { ...@@ -367,10 +313,10 @@ exports.on = function (event, callback, scope) {
/** /**
* Unregister callback for given event. * Unregister callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback *
* The function to be exec as callback * @return [ Void ]
*/ */
exports.un = function (event, callback) { exports.un = function (event, callback) {
this.core.un(event, callback); this.core.un(event, callback);
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
<body> <body>
<div> <div>
<div class="app"> <div class="app">
<h1>Local Notification Example</h1> <h1>Notification Example</h1>
<div id="deviceready" class="blink"> <div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p> <p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p> <p class="event received">Device is Ready</p>
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
<a id="sched_multi" class="button orange">Multiple</a> <a id="sched_multi" class="button orange">Multiple</a>
</div> </div>
<div class="container"> <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> <a id="sched_interval" class="button orange">Interval</a>
</div> </div>
<h2 class="section">Update</h2> <h2 class="section">Update</h2>
...@@ -85,7 +85,7 @@ ...@@ -85,7 +85,7 @@
<a id="triggered_ids" class="button grey">Triggered</a> <a id="triggered_ids" class="button grey">Triggered</a>
</div> </div>
<div class="container"> <div class="container">
<a id="all_ids" class="button grey">All</a> <a id="ids" class="button grey">All</a>
</div> </div>
<h2 class="section">Notifications</h2> <h2 class="section">Notifications</h2>
<div class="container"> <div class="container">
...@@ -93,11 +93,11 @@ ...@@ -93,11 +93,11 @@
<a id="triggered_nots" class="button grey">Triggered</a> <a id="triggered_nots" class="button grey">Triggered</a>
</div> </div>
<div class="container"> <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> <a id="multiple_nots" class="button grey">Multiple</a>
</div> </div>
<div class="container"> <div class="container">
<a id="all_nots" class="button grey">All</a> <a id="notifications" class="button grey">All</a>
</div> </div>
<h2 class="section">Defaults</h2> <h2 class="section">Defaults</h2>
<div class="container"> <div class="container">
......
...@@ -36,6 +36,7 @@ var app = { ...@@ -36,6 +36,7 @@ var app = {
onDeviceReady: function() { onDeviceReady: function() {
app.receivedEvent('deviceready'); app.receivedEvent('deviceready');
app.pluginInitialize(); app.pluginInitialize();
app.bindNotificationEvents();
}, },
// Update DOM on a Received Event // Update DOM on a Received Event
receivedEvent: function(id) { receivedEvent: function(id) {
...@@ -50,16 +51,240 @@ var app = { ...@@ -50,16 +51,240 @@ var app = {
}, },
// Initialize plugin // Initialize plugin
pluginInitialize: function() { pluginInitialize: function() {
document.getElementById('granted').onclick = app.hasPermission; document.getElementById('granted').onclick = app.hasPermission;
document.getElementById('request').onclick = app.askPermission; 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 // Check permissions to read accounts
hasPermission: function () { hasPermission: function () {
cordova.plugins.notification.local.hasPermission(showToast); cordova.plugins.notification.local.hasPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
}, },
// Request permissions to read accounts // Request permissions to read accounts
askPermission: function () { 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) { ...@@ -56,66 +56,39 @@ exports.requestPermission = function (callback, scope) {
exec(fn, null, 'LocalNotification', 'request', []); exec(fn, null, 'LocalNotification', 'request', []);
}; };
// /** /**
// * Returns the default settings. * Schedule notifications.
// * *
// * @return {Object} * @param [ Array ] notifications The notifications to schedule.
// */ * @param [ Function ] callback The function to be exec as the callback.
// exports.getDefaults = function () { * @param [ Object ] scope The callback function's scope.
// return this._defaults; * @param [ Object ] args Optional flags how to schedule.
// }; *
* @return [ Void ]
// /** */
// * Overwrite default settings. exports.schedule = function (msgs, callback, scope, args) {
// * var fn = function (granted) {
// * @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) {
// 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++) { for (var i = 0; i < notifications.length; i++) {
// var notification = notifications[i]; var notification = notifications[i];
// this.mergeWithDefaults(notification); this.mergeWithDefaults(notification);
// this.convertProperties(notification); this.convertProperties(notification);
// } }
// this.exec('schedule', notifications, callback, scope); this.exec('schedule', notifications, callback, scope);
// }; };
// if (args && args.skipPermission) { if (args && args.skipPermission) {
// fn.call(this, true); fn.call(this, true);
// } else { } else {
// this.registerPermission(fn, this); this.requestPermission(fn, this);
// } }
// }; };
// /** // /**
// * Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
...@@ -153,340 +126,348 @@ exports.requestPermission = function (callback, scope) { ...@@ -153,340 +126,348 @@ exports.requestPermission = function (callback, scope) {
// } // }
// }; // };
// /** /**
// * Clear the specified notification. * Clear the specified notifications by id.
// * *
// * @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A function to be called after the notification has been cleared *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.clear = function (ids, callback, scope) {
// exports.clear = function (ids, callback, scope) { ids = Array.isArray(ids) ? ids : [ids];
// ids = Array.isArray(ids) ? ids : [ids]; ids = this.convertIds(ids);
// ids = this.convertIds(ids);
// this.exec('clear', ids, callback, scope); this.exec('clear', ids, callback, scope);
// }; };
// /** /**
// * Clear all previously sheduled notifications. * Clear all triggered notifications.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
// this.exec('clearAll', null, callback, scope); this.exec('clearAll', null, callback, scope);
// }; };
// /** /**
// * Cancel the specified notifications. * Clear the specified notifications by id.
// * *
// * @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
// * The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A function to be called after the notifications has been canceled *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.cancel = function (ids, callback, scope) {
// exports.cancel = function (ids, callback, scope) { ids = Array.isArray(ids) ? ids : [ids];
// ids = Array.isArray(ids) ? ids : [ids]; ids = this.convertIds(ids);
// ids = this.convertIds(ids);
// this.exec('cancel', ids, callback, scope); this.exec('cancel', ids, callback, scope);
// }; };
// /** /**
// * Remove all previously registered notifications. * Cancel all scheduled notifications.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A function to be called after all notifications have been canceled * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.cancelAll = function (callback, scope) { exports.cancelAll = function (callback, scope) {
// this.exec('cancelAll', null, callback, scope); this.exec('cancelAll', null, callback, scope);
// }; };
// /** /**
// * Check if a notification with an ID is present. * Check if a notification is present.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.isPresent = function (id, callback, scope) {
// exports.isPresent = function (id, callback, scope) { this.exec('isPresent', id, callback, scope);
// this.exec('isPresent', id || 0, callback, scope); };
// };
// /** /**
// * Check if a notification with an ID is scheduled. * Check if a notification is scheduled.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.isScheduled = function (id, callback, scope) {
// exports.isScheduled = function (id, callback, scope) { this.exec('isScheduled', id, callback, scope);
// this.exec('isScheduled', id || 0, callback, scope); };
// };
// /** /**
// * Check if a notification with an ID was triggered. * Check if a notification was triggered.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.isTriggered = function (id, callback, scope) {
// exports.isTriggered = function (id, callback, scope) { this.exec('isTriggered', id, callback, scope);
// this.exec('isTriggered', id || 0, callback, scope); };
// };
// * /**
// * List all local notification IDs. * List of all notification ids.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @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`. * List of all scheduled notification IDs.
// */ *
// exports.getIds = function () { * @param [ Function ] callback The function to be exec as the callback.
// this.getAllIds.apply(this, arguments); * @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. * List of all triggered notification IDs.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.getScheduledIds = function (callback, scope) { exports.getTriggeredIds = function (callback, scope) {
// this.exec('getScheduledIds', null, callback, scope); this.exec('triggeredIds', null, callback, scope);
// }; };
// /** /**
// * List all triggered notification IDs. * List of local notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getTriggeredIds = function (callback, scope) { * @return [ Void ]
// this.exec('getTriggeredIds', null, callback, scope); */
// }; exports.get = function () {
var args = Array.apply(null, arguments);
// /** if (typeof args[0] == 'function') {
// * Property list for given local notifications. args.unshift([]);
// * 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') { var ids = args[0],
// args.unshift([]); callback = args[1],
// } scope = args[2];
// var ids = args[0], if (!Array.isArray(ids)) {
// callback = args[1], this.exec('notification', Number(ids), callback, scope);
// scope = args[2]; return;
}
// if (!Array.isArray(ids)) { ids = this.convertIds(ids);
// this.exec('getSingle', Number(ids), callback, scope);
// return;
// }
// 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. * List of scheduled notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getAll = function (callback, scope) { * @return [ Void ]
// this.exec('getAll', null, callback, scope); */
// }; exports.getScheduled = function () {
var args = Array.apply(null, arguments);
// /** if (typeof args[0] == 'function') {
// * Property list for given scheduled notifications. args.unshift([]);
// * 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') { var ids = args[0],
// args.unshift([]); callback = args[1],
// } scope = args[2];
// var ids = args[0], if (!Array.isArray(ids)) {
// callback = args[1], ids = [ids];
// scope = args[2]; }
// if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
// ids = [ids]; this.exec('scheduledNotification', Number(ids), callback, scope);
// } return;
}
// if (!Array.isArray(ids)) { ids = this.convertIds(ids);
// this.exec('getSingleScheduled', Number(ids), callback, scope);
// return;
// }
// 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. * List of triggered notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getAllScheduled = function (callback, scope) { * @return [ Void ]
// this.exec('getScheduled', null, callback, scope); */
// }; exports.getTriggered = function () {
var args = Array.apply(null, arguments);
// /** if (typeof args[0] == 'function') {
// * Property list for given triggered notifications. args.unshift([]);
// * 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') { var ids = args[0],
// args.unshift([]); callback = args[1],
// } scope = args[2];
// var ids = args[0], if (!Array.isArray(ids)) {
// callback = args[1], ids = [ids];
// scope = args[2]; }
// if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
// ids = [ids]; this.exec('triggeredNotification', Number(ids), callback, scope);
// } return;
}
// if (!Array.isArray(ids)) { ids = this.convertIds(ids);
// this.exec('getSingleTriggered', Number(ids), callback, scope);
// return;
// }
// 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. * The (platform specific) default settings.
// * *
// * @param {Function} callback * @return [ Object ]
// * A callback function to be called with the list */
// * @param {Object?} scope exports.getDefaults = function () {
// * The scope for the callback function return this._defaults;
// */ };
// exports.getAllTriggered = function (callback, scope) {
// this.exec('getTriggered', null, callback, scope);
// };
/**
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.setDefaults = function (newDefaults) {
var defaults = this.getDefaults();
// /********** for (var key in defaults) {
// * EVENTS * if (newDefaults.hasOwnProperty(key)) {
// **********/ defaults[key] = newDefaults[key];
}
}
};
// /** /**
// * Register callback for given event. * Register callback for given event.
// * *
// * @param {String} event * @param [ String ] event The name of the event.
// * The event's name * @param [ Function ] callback The function to be exec as callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * The function to be exec as callback *
// * @param {Object?} scope * @return [ Void ]
// * The callback function's scope */
// */ exports.on = function (event, callback, scope) {
// exports.on = function (event, callback, scope) {
// if (typeof callback !== "function") if (typeof callback !== "function")
// return; return;
// if (!this._listener[event]) { if (!this._listener[event]) {
// 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. * Unregister callback for given event.
// * *
// * @param {String} event * @param [ String ] event The name of the event.
// * The event's name * @param [ Function ] callback The function to be exec as callback.
// * @param {Function} callback *
// * The function to be exec as callback * @return [ Void ]
// */ */
// exports.un = function (event, callback) { exports.un = function (event, callback) {
// var listener = this._listener[event]; var listener = this._listener[event];
// if (!listener) if (!listener)
// return; return;
// for (var i = 0; i < listener.length; i++) { for (var i = 0; i < listener.length; i++) {
// var fn = listener[i][0]; var fn = listener[i][0];
// if (fn == callback) { if (fn == callback) {
// listener.splice(i, 1); listener.splice(i, 1);
// break; break;
// } }
// } }
// }; };
}); });
...@@ -15,166 +15,143 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", func ...@@ -15,166 +15,143 @@ cordova.define("cordova-plugin-local-notifications.LocalNotification.Util", func
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*/ */
// var exec = require('cordova/exec'),
// channel = require('cordova/channel'); var exec = require('cordova/exec'),
channel = require('cordova/channel');
// /*********** // Default values
// * MEMBERS * exports._defaults = {
// ***********/ text: '',
title: '',
// // Default values sound: 'res://platform_default',
// exports._defaults = { badge: 0,
// text: '', id: 0,
// title: '', data: undefined,
// sound: 'res://platform_default', every: undefined,
// badge: 0, at: undefined
// id: 0, };
// data: undefined,
// every: undefined, // Listener
// at: undefined exports._listener = {};
// };
/**
// // listener * Merge platform specific properties into the default ones.
// exports._listener = {}; *
* @return [ Void ]
*/
// /******** exports.applyPlatformSpecificOptions = function () {
// * UTIL * var defaults = this._defaults;
// ********/
switch (device.platform) {
// /** case 'Android':
// * Merge platform specific properties into the default ones. defaults.icon = 'res://ic_popup_reminder';
// * defaults.smallIcon = undefined;
// * @return {Object} defaults.ongoing = false;
// * The default properties for the platform defaults.autoClear = true;
// */ defaults.led = undefined;
// exports.applyPlatformSpecificOptions = function () { defaults.color = undefined;
// var defaults = this._defaults; break;
case 'iOS':
// switch (device.platform) { defaults.attachments = undefined;
// case 'Android': break;
// defaults.icon = 'res://ic_popup_reminder'; }
// defaults.smallIcon = undefined; };
// defaults.ongoing = false;
// defaults.autoClear = true; /**
// defaults.led = undefined; * Merge custom properties with the default values.
// defaults.color = undefined; *
// break; * @param [ Object ] options Set of custom values.
// } *
* @retrun [ Object ]
// return defaults; */
// }; exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults();
// /**
// * Merge custom properties with the default values. options.at = this.getValueFor(options, 'at', 'firstAt', 'date');
// * options.text = this.getValueFor(options, 'text', 'message');
// * @param {Object} options options.data = this.getValueFor(options, 'data', 'json');
// * Set of custom values
// * if (defaults.hasOwnProperty('autoClear')) {
// * @retrun {Object} options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
// * The merged property list }
// */
// exports.mergeWithDefaults = function (options) { if (options.autoClear !== true && options.ongoing) {
// var defaults = this.getDefaults(); options.autoClear = false;
}
// options.at = this.getValueFor(options, 'at', 'firstAt', 'date');
// options.text = this.getValueFor(options, 'text', 'message'); if (options.at === undefined || options.at === null) {
// options.data = this.getValueFor(options, 'data', 'json'); options.at = new Date();
}
// if (defaults.hasOwnProperty('autoClear')) {
// options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel'); for (var key in defaults) {
// } if (options[key] === null || options[key] === undefined) {
if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
// if (options.autoClear !== true && options.ongoing) { options[key] = undefined;
// options.autoClear = false; } else {
// } options[key] = defaults[key];
}
// if (options.at === undefined || options.at === null) { }
// options.at = new Date(); }
// }
for (key in options) {
// for (var key in defaults) { if (!defaults.hasOwnProperty(key)) {
// if (options[key] === null || options[key] === undefined) { delete options[key];
// if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) { console.warn('Unknown property: ' + key);
// options[key] = undefined; }
// } else { }
// options[key] = defaults[key];
// } return options;
// } };
// }
/**
// for (key in options) { * Convert the passed values to their required type.
// if (!defaults.hasOwnProperty(key)) { *
// delete options[key]; * @param [ Object ] options Properties to convert for.
// console.warn('Unknown property: ' + key); *
// } * @return [ Object ] The converted property list
// } */
exports.convertProperties = function (options) {
// return options;
// }; if (options.id) {
if (isNaN(options.id)) {
// /** options.id = this.getDefaults().id;
// * Convert the passed values to their required type. console.warn('Id is not a number: ' + options.id);
// * } else {
// * @param {Object} options options.id = Number(options.id);
// * Set of custom values }
// * }
// * @retrun {Object}
// * The converted property list if (options.title) {
// */ options.title = options.title.toString();
// exports.convertProperties = function (options) { }
// if (options.id) { if (options.text) {
// if (isNaN(options.id)) { options.text = options.text.toString();
// options.id = this.getDefaults().id; }
// console.warn('Id is not a number: ' + options.id);
// } else { if (options.badge) {
// options.id = Number(options.id); if (isNaN(options.badge)) {
// } options.badge = this.getDefaults().badge;
// } console.warn('Badge number is not a number: ' + options.id);
} else {
// if (options.title) { options.badge = Number(options.badge);
// options.title = options.title.toString(); }
// } }
// if (options.text) { if (options.at) {
// options.text = options.text.toString(); if (typeof options.at == 'object') {
// } options.at = options.at.getTime();
}
// if (options.badge) {
// if (isNaN(options.badge)) { options.at = Math.round(options.at/1000);
// options.badge = this.getDefaults().badge; }
// console.warn('Badge number is not a number: ' + options.id);
// } else { if (typeof options.data == 'object') {
// options.badge = Number(options.badge); options.data = JSON.stringify(options.data);
// } }
// }
return options;
// 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;
// };
/** /**
* Create a callback function to get executed within a specific scope. * Create a callback function to get executed within a specific scope.
...@@ -194,110 +171,103 @@ exports.createCallbackFn = function (fn, scope) { ...@@ -194,110 +171,103 @@ exports.createCallbackFn = function (fn, scope) {
}; };
}; };
// /** /**
// * Convert the IDs to numbers. * Convert the IDs to numbers.
// * *
// * @param {String/Number[]} ids * @param [ Array ] ids
// * *
// * @return Array of Numbers * @return [ Array<Number> ]
// */ */
// exports.convertIds = function (ids) { exports.convertIds = function (ids) {
// var convertedIds = []; var convertedIds = [];
// for (var i = 0; i < ids.length; i++) { for (var i = 0; i < ids.length; i++) {
// convertedIds.push(Number(ids[i])); convertedIds.push(Number(ids[i]));
// } }
// return convertedIds; return convertedIds;
// }; };
// /** /**
// * First found value for the given keys. * First found value for the given keys.
// * *
// * @param {Object} options * @param [ Object ] options Object with key-value properties.
// * Object with key-value properties * @param [ *Array<String> ] keys List of keys.
// * @param {String[]} keys* *
// * Key list * @return [ Object ]
// */ */
// exports.getValueFor = function (options) { exports.getValueFor = function (options) {
// var keys = Array.apply(null, arguments).slice(1); var keys = Array.apply(null, arguments).slice(1);
// for (var i = 0; i < keys.length; i++) { for (var i = 0; i < keys.length; i++) {
// var key = keys[i]; var key = keys[i];
// if (options.hasOwnProperty(key)) { if (options.hasOwnProperty(key)) {
// return options[key]; return options[key];
// } }
// } }
// }; };
// /** /**
// * Fire event with given arguments. * Fire the event with given arguments.
// * *
// * @param {String} event * @param [ String ] event The event's name.
// * The event's name * @param [ *Array] args The callback's arguments.
// * @param {args*} *
// * The callback's arguments * @return [ Void]
// */ */
// exports.fireEvent = function (event) { exports.fireEvent = function (event) {
// var args = Array.apply(null, arguments).slice(1), var args = Array.apply(null, arguments).slice(1),
// listener = this._listener[event]; listener = this._listener[event];
// if (!listener) if (!listener)
// return; return;
// for (var i = 0; i < listener.length; i++) { for (var i = 0; i < listener.length; i++) {
// var fn = listener[i][0], var fn = listener[i][0],
// scope = listener[i][1]; scope = listener[i][1];
// fn.apply(scope, args); fn.apply(scope, args);
// } }
// }; };
// /** /**
// * Execute the native counterpart. * Execute the native counterpart.
// * *
// * @param {String} action * @param [ String ] action The name of the action.
// * The name of the action * @param [ Array ] args Array of arguments.
// * @param args[] * @param [ Function] callback The callback function.
// * Array of arguments * @param [ Object ] scope The scope for the function.
// * @param {Function} callback *
// * The callback function * @return [ Void ]
// * @param {Object} scope */
// * The scope for the function exports.exec = function (action, args, callback, scope) {
// */ var fn = this.createCallbackFn(callback, scope),
// exports.exec = function (action, args, callback, scope) { params = [];
// var fn = this.createCallbackFn(callback, scope),
// params = []; if (Array.isArray(args)) {
params = args;
// if (Array.isArray(args)) { } else if (args) {
// params = args; params.push(args);
// } else if (args) { }
// params.push(args);
// } exec(fn, null, 'LocalNotification', action, params);
};
// 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.
// * HOOKS * exec(null, null, 'LocalNotification', 'deviceready', []);
// *********/ });
// // Called after 'deviceready' event // Called before 'deviceready' event
// channel.deviceready.subscribe(function () { channel.onCordovaReady.subscribe(function () {
// // Device is ready now, the listeners are registered // Device plugin is ready now
// // and all queued events can be executed. channel.onCordovaInfoReady.subscribe(function () {
// exec(null, null, 'LocalNotification', 'deviceready', []); // Merge platform specifics into defaults
// }); exports.applyPlatformSpecificOptions();
});
// // 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) { ...@@ -40,40 +40,19 @@ exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope); this.core.requestPermission(callback, scope);
}; };
// /** /**
// * Returns the default settings. * Schedule notifications.
// * *
// * @return {Object} * @param [ Array ] notifications The notifications to schedule.
// */ * @param [ Function ] callback The function to be exec as the callback.
// exports.getDefaults = function () { * @param [ Object ] scope The callback function's scope.
// return this.core.getDefaults(); * @param [ Object ] args Optional flags how to schedule.
// }; *
* @return [ Void ]
// /** */
// * Overwrite default settings. exports.schedule = function (notifications, callback, scope, args) {
// * this.core.schedule(notifications, callback, scope, args);
// * @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);
// };
// /** // /**
// * Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
...@@ -92,248 +71,255 @@ exports.requestPermission = function (callback, scope) { ...@@ -92,248 +71,255 @@ exports.requestPermission = function (callback, scope) {
// this.core.update(notifications, callback, scope, args); // this.core.update(notifications, callback, scope, args);
// }; // };
// /** /**
// * Clear the specified notification. * Clear the specified notifications by id.
// * *
// * @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A function to be called after the notification has been cleared *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.clear = function (ids, callback, scope) {
// exports.clear = function (ids, callback, scope) { this.core.clear(ids, callback, scope);
// this.core.clear(ids, callback, scope); };
// };
// /** /**
// * Clear all previously sheduled notifications. * Clear all triggered notifications.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
// this.core.clearAll(callback, scope); this.core.clearAll(callback, scope);
// }; };
// /** /**
// * Cancel the specified notifications. * Cancel the specified notifications by id.
// * *
// * @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
// * The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A function to be called after the notifications has been canceled *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.cancel = function (ids, callback, scope) {
// exports.cancel = function (ids, callback, scope) { this.core.cancel(ids, callback, scope);
// this.core.cancel(ids, callback, scope); };
// };
// /** /**
// * Remove all previously registered notifications. * Cancel all scheduled notifications.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A function to be called after all notifications have been canceled * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.cancelAll = function (callback, scope) { exports.cancelAll = function (callback, scope) {
// this.core.cancelAll(callback, scope); this.core.cancelAll(callback, scope);
// }; };
// /** /**
// * Check if a notification with an ID is present. * Check if a notification is present.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.isPresent = function (id, callback, scope) {
// exports.isPresent = function (id, callback, scope) { this.core.isPresent(id, callback, scope);
// this.core.isPresent(id, callback, scope); };
// };
// /** /**
// * Check if a notification with an ID is scheduled. * Check if a notification is scheduled.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
// */ exports.isScheduled = function (id, callback, scope) {
// exports.isScheduled = function (id, callback, scope) { this.core.isScheduled(id, callback, scope);
// this.core.isScheduled(id, callback, scope); };
// };
// * /**
// * Check if a notification with an ID was triggered. * Check if a notification was triggered.
// * *
// * @param {String} id * @param [ Int ] id The ID of the notification.
// * The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * A callback function to be called with the list *
// * @param {Object?} scope * @return [ Void ]
// * The scope for the callback function */
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. * Alias for `getAllIds`.
// * */
// * @param {Function} callback exports.getIds = function () {
// * A callback function to be called with the list this.getAllIds.apply(this, arguments);
// * @param {Object?} scope };
// * The scope for the callback function
// */
// exports.getAllIds = function (callback, scope) {
// this.core.getAllIds(callback, scope);
// };
// /** /**
// * Alias for `getAllIds`. * List of all scheduled notification IDs.
// */ *
// exports.getIds = function () { * @param [ Function ] callback The function to be exec as the callback.
// this.getAllIds.apply(this, arguments); * @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. * List of all triggered notification IDs.
// * *
// * @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
// * A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
// * @param {Object?} scope *
// * The scope for the callback function * @return [ Void ]
// */ */
// exports.getScheduledIds = function (callback, scope) { exports.getTriggeredIds = function (callback, scope) {
// this.core.getScheduledIds(callback, scope); this.core.getTriggeredIds(callback, scope);
// }; };
// /** /**
// * List all triggered notification IDs. * List of local notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getTriggeredIds = function (callback, scope) { * @return [ Void ]
// this.core.getTriggeredIds(callback, scope); */
// }; exports.get = function (ids, callback, scope) {
this.core.get(ids, callback, scope);
};
// /** /**
// * Property list for given local notifications. * List for all notifications.
// * If called without IDs, all notification will be returned. *
// * * @param [ Function ] callback The function to be exec as the callback.
// * @param {Number[]?} ids * @param [ Object ] scope The callback function's scope.
// * Set of notification IDs *
// * @param {Function} callback * @return [ Void ]
// * A callback function to be called with the list */
// * @param {Object?} scope exports.getAll = function (callback, scope) {
// * The scope for the callback function this.core.getAll(callback, scope);
// */ };
// exports.get = function () {
// this.core.get.apply(this.core, arguments);
// };
// /** /**
// * Property list for all local notifications. * List of scheduled notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getAll = function (callback, scope) { * @return [ Void ]
// this.core.getAll(callback, scope); */
// }; exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled(ids, callback, scope);
};
// /** /**
// * Property list for given scheduled notifications. * List of all scheduled notifications.
// * If called without IDs, all notification will be returned. *
// * * @param [ Function ] callback The function to be exec as the callback.
// * @param {Number[]?} ids * @param [ Object ] scope The callback function's scope.
// * Set of notification IDs */
// * @param {Function} callback exports.getAllScheduled = function (callback, scope) {
// * A callback function to be called with the list this.core.getAllScheduled(callback, scope);
// * @param {Object?} scope };
// * The scope for the callback function
// */
// exports.getScheduled = function () {
// this.core.getScheduled.apply(this.core, arguments);
// };
// /** /**
// * Property list for all scheduled notifications. * List of triggered notifications specified by id.
// * * If called without IDs, all notification will be returned.
// * @param {Function} callback *
// * A callback function to be called with the list * @param [ Array<Int> ] ids The IDs of the notifications.
// * @param {Object?} scope * @param [ Function ] callback The function to be exec as the callback.
// * The scope for the callback function * @param [ Object ] scope The callback function's scope.
// */ *
// exports.getAllScheduled = function (callback, scope) { * @return [ Void ]
// this.core.getAllScheduled(callback, scope); */
// }; exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered(ids, callback, scope);
};
// /** /**
// * Property list for given triggered notifications. * List of all triggered notifications.
// * If called without IDs, all notification will be returned. *
// * * @param [ Function ] callback The function to be exec as the callback.
// * @param {Number[]?} ids * @param [ Object ] scope The callback function's scope.
// * Set of notification IDs */
// * @param {Function} callback exports.getAllTriggered = function (callback, scope) {
// * A callback function to be called with the list this.core.getAllTriggered(callback, scope);
// * @param {Object?} scope };
// * The scope for the callback function
// */
// exports.getTriggered = function () {
// this.core.getTriggered.apply(this.core, arguments);
// };
// /** /**
// * Property list for all triggered notifications. * The (platform specific) default settings.
// * *
// * @param {Function} callback * @return [ Object ]
// * A callback function to be called with the list */
// * @param {Object?} scope exports.getDefaults = function () {
// * The scope for the callback function return this.core.getDefaults();
// */ };
// exports.getAllTriggered = function (callback, scope) {
// this.core.getAllTriggered(callback, scope);
// };
// /** /**
// * Register callback for given event. * Overwrite default settings.
// * *
// * @param {String} event * @param [ Object ] newDefaults New default values.
// * The event's name *
// * @param {Function} callback * @return [ Void ]
// * The function to be exec as callback */
// * @param {Object?} scope exports.setDefaults = function (defaults) {
// * The callback function's scope this.core.setDefaults(defaults);
// */ };
// exports.on = function (event, callback, scope) {
// this.core.on(event, callback, scope);
// };
// /** /**
// * Unregister callback for given event. * Register callback for given event.
// * *
// * @param {String} event * @param [ String ] event The name of the event.
// * The event's name * @param [ Function ] callback The function to be exec as callback.
// * @param {Function} callback * @param [ Object ] scope The callback function's scope.
// * The function to be exec as callback *
// */ * @return [ Void ]
// exports.un = function (event, callback) { */
// this.core.un(event, callback); 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 @@ ...@@ -27,7 +27,6 @@
<!-- dependencies --> <!-- dependencies -->
<dependency id="cordova-plugin-device" /> <dependency id="cordova-plugin-device" />
<!-- <dependency id="cordova-plugin-app-event" /> -->
<!-- js --> <!-- js -->
<js-module src="www/local-notification.js" name="LocalNotification"> <js-module src="www/local-notification.js" name="LocalNotification">
...@@ -59,17 +58,17 @@ ...@@ -59,17 +58,17 @@
<header-file src="src/ios/APPLocalNotification.h" /> <header-file src="src/ios/APPLocalNotification.h" />
<source-file src="src/ios/APPLocalNotification.m" /> <source-file src="src/ios/APPLocalNotification.m" />
<!-- <header-file src="src/ios/APPLocalNotificationOptions.h" /> <header-file src="src/ios/APPNotificationContent.h" />
<source-file src="src/ios/APPLocalNotificationOptions.m" /> <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" /> <header-file src="src/ios/UNUserNotificationCenter+APPLocalNotification.h" />
<source-file src="src/ios/UNUserNotificationCenter+APPLocalNotification.m" /> <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" /> <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> </platform>
......
/* /*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved. * Copyright (c) 2013 by appPlant GmbH. All rights reserved.
* *
* @APPPLANT_LICENSE_HEADER_START@ * @APPPLANT_LICENSE_HEADER_START@
* *
...@@ -21,7 +21,6 @@ ...@@ -21,7 +21,6 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h> #import <Cordova/CDVPlugin.h>
@import UserNotifications; @import UserNotifications;
...@@ -31,23 +30,23 @@ ...@@ -31,23 +30,23 @@
// Execute all queued events // Execute all queued events
- (void) deviceready:(CDVInvokedUrlCommand*)command; - (void) deviceready:(CDVInvokedUrlCommand*)command;
// Inform if the app has the permission to show notifications // Check permission to show notifications
- (void) hasPermission:(CDVInvokedUrlCommand*)command; - (void) check:(CDVInvokedUrlCommand*)command;
// Register permission to show notifications // Request permission to show notifications
- (void) registerPermission:(CDVInvokedUrlCommand*)command; - (void) request:(CDVInvokedUrlCommand*)command;
// Schedule set of notifications // Schedule notifications
- (void) schedule:(CDVInvokedUrlCommand*)command; - (void) schedule:(CDVInvokedUrlCommand*)command;
// Update set of notifications //// Update set of notifications
- (void) update:(CDVInvokedUrlCommand*)command; //- (void) update:(CDVInvokedUrlCommand*)command;
// Cancel set of notifications // Clear notifications by id
- (void) cancel:(CDVInvokedUrlCommand*)command;
// Cancel all notifications
- (void) cancelAll:(CDVInvokedUrlCommand*)command;
// Clear set of notifications
- (void) clear:(CDVInvokedUrlCommand*)command; - (void) clear:(CDVInvokedUrlCommand*)command;
// Clear all notifications // Clear all notifications
- (void) clearAll:(CDVInvokedUrlCommand*)command; - (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 // If a notification with an ID is present
- (void) isPresent:(CDVInvokedUrlCommand*)command; - (void) isPresent:(CDVInvokedUrlCommand*)command;
...@@ -56,25 +55,25 @@ ...@@ -56,25 +55,25 @@
// If a notification with an ID is triggered // If a notification with an ID is triggered
- (void) isTriggered:(CDVInvokedUrlCommand*)command; - (void) isTriggered:(CDVInvokedUrlCommand*)command;
// List all ids from all local notifications // List of all notification IDs
- (void) getAllIds:(CDVInvokedUrlCommand*)command; - (void) ids:(CDVInvokedUrlCommand*)command;
// List all ids from all pending notifications // List of all scheduled notification IDs
- (void) getScheduledIds:(CDVInvokedUrlCommand*)command; - (void) scheduledIds:(CDVInvokedUrlCommand*)command;
// List all ids from all triggered notifications // List of all triggered notification IDs
- (void) getTriggeredIds:(CDVInvokedUrlCommand*)command; - (void) triggeredIds:(CDVInvokedUrlCommand*)command;
// Propertys for given local notification // Notification by id
- (void) getSingle:(CDVInvokedUrlCommand*)command; - (void) notification:(CDVInvokedUrlCommand*)command;
// Propertya for given scheduled notification // Scheduled notification by id
- (void) getSingleScheduled:(CDVInvokedUrlCommand*)command; - (void) scheduledNotification:(CDVInvokedUrlCommand*)command;
// Propertys for given triggered notification // Triggered notification by id
- (void) getSingleTriggered:(CDVInvokedUrlCommand*)command; - (void) triggeredNotification:(CDVInvokedUrlCommand*)command;
// Property list for given local notifications // List of notifications by id
- (void) getAll:(CDVInvokedUrlCommand*)command; - (void) notifications:(CDVInvokedUrlCommand*)command;
// Property list for given scheduled notifications // List of scheduled notifications by id
- (void) getScheduled:(CDVInvokedUrlCommand*)command; - (void) scheduledNotifications:(CDVInvokedUrlCommand*)command;
// Property list for given triggered notifications // List of triggered notifications by id
- (void) getTriggered:(CDVInvokedUrlCommand*)command; - (void) triggeredNotifications:(CDVInvokedUrlCommand*)command;
@end @end
/* /*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved. * Copyright (c) 2013 by appPlant GmbH. All rights reserved.
* *
* @APPPLANT_LICENSE_HEADER_START@ * @APPPLANT_LICENSE_HEADER_START@
* *
...@@ -22,31 +22,18 @@ ...@@ -22,31 +22,18 @@
*/ */
#import "APPLocalNotification.h" #import "APPLocalNotification.h"
#import "APPLocalNotificationOptions.h" #import "APPNotificationOptions.h"
#import "UNUserNotificationCenter+APPLocalNotification.h" #import "UNUserNotificationCenter+APPLocalNotification.h"
#import "UNNotificationRequest+APPLocalNotification.h" #import "UNNotificationRequest+APPLocalNotification.h"
#import "UNMutableNotificationContent+APPLocalNotification.h" #import "APPNotificationContent.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)
@interface APPLocalNotification () @interface APPLocalNotification ()
// Property reader for [self app] @property (strong, nonatomic) UIApplication* app;
@property (readonly, getter=app) UIApplication* app; @property (strong, nonatomic) UNUserNotificationCenter* center;
// Property reader for [self center]
@property (readonly, getter=center) UNUserNotificationCenter* center;
// All events will be queued until deviceready has been fired
@property (readwrite, assign) BOOL deviceready; @property (readwrite, assign) BOOL deviceready;
// Event queue
@property (readonly, nonatomic, retain) NSMutableArray* eventQueue; @property (readonly, nonatomic, retain) NSMutableArray* eventQueue;
// IOS9: TODO remove later
@property (nonatomic, retain) CDVInvokedUrlCommand* command;
@end @end
@implementation APPLocalNotification @implementation APPLocalNotification
...@@ -58,6 +45,8 @@ ...@@ -58,6 +45,8 @@
/** /**
* Execute all queued events. * Execute all queued events.
*
* @return [ Void ]
*/ */
- (void) deviceready:(CDVInvokedUrlCommand*)command - (void) deviceready:(CDVInvokedUrlCommand*)command
{ {
...@@ -71,185 +60,146 @@ ...@@ -71,185 +60,146 @@
} }
/** /**
* Schedule a set of notifications. * Schedule notifications.
*
* @param [Array<Hash>] properties A list of key-value properties.
* *
* @param properties * @return [ Void ]
* A dict of properties for each notification
*/ */
- (void) schedule:(CDVInvokedUrlCommand*)command - (void) schedule:(CDVInvokedUrlCommand*)command
{ {
NSArray* notifications = command.arguments; NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { for (NSDictionary* options in notifications) {
for (NSDictionary* options in notifications) { APPNotificationContent* notification;
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]; notification = [[APPNotificationContent alloc]
}]; initWithOptions:options];
}
/** [self scheduleNotification:notification];
* 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]; [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 ids * @param [ Array<Int> ] The IDs of the notifications to clear.
* The IDs of the notifications *
* @return [ Void ]
*/ */
- (void) cancel:(CDVInvokedUrlCommand*)command - (void) clear:(CDVInvokedUrlCommand*)command
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { for (NSNumber* id in command.arguments) {
for (NSNumber* id in command.arguments) { UNNotificationRequest* notification;
UNNotificationRequest* notification;
notification = [self.center getNotificationWithId:id];
notification = [self.center getNotificationWithId:id];
if (!notification)
if (!notification) continue;
continue;
[self.center clearNotification:notification];
[self.center cancelNotification:notification]; [self fireEvent:@"clear" notification: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]; [self execCallback:command];
}]; }];
} }
/** /**
* Cancel all local notifications. * Clear all local notifications.
*
* @return [ Void ]
*/ */
- (void) cancelAll:(CDVInvokedUrlCommand*)command - (void) clearAll:(CDVInvokedUrlCommand*)command
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
[self cancelAllNotifications]; [self.center clearAllNotifications];
[self fireEvent:@"cancelall"]; [self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"clearall"];
[self execCallback:command]; [self execCallback:command];
}]; }];
} }
/** /**
* Clear a set of notifications. * Cancel notifications by id.
*
* @param [ Array<Int> ] The IDs of the notifications to clear.
* *
* @param ids * @return [ Void ]
* The IDs of the notifications
*/ */
- (void) clear:(CDVInvokedUrlCommand*)command - (void) cancel:(CDVInvokedUrlCommand*)command
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { for (NSNumber* id in command.arguments) {
for (NSNumber* id in command.arguments) { UNNotificationRequest* notification;
UNNotificationRequest* notification;
notification = [self.center getNotificationWithId:id];
notification = [self.center getNotificationWithId:id];
if (!notification)
if (!notification) continue;
continue;
[self.center cancelNotification:notification];
[self.center clearNotification:notification]; [self fireEvent:@"cancel" notification: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]; [self execCallback:command];
...@@ -257,13 +207,16 @@ ...@@ -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.commandDelegate runInBackground:^{
[self clearAllNotifications]; [self.center cancelAllNotifications];
[self fireEvent:@"clearall"]; [self.app setApplicationIconBadgeNumber:0];
[self fireEvent:@"cancelall"];
[self execCallback:command]; [self execCallback:command];
}]; }];
} }
...@@ -271,58 +224,52 @@ ...@@ -271,58 +224,52 @@
/** /**
* If a notification by ID is present. * If a notification by ID is present.
* *
* @param id * @param [ Number ]id The ID of the notification.
* The ID of the notification *
* @return [ Void ]
*/ */
- (void) isPresent:(CDVInvokedUrlCommand *)command - (void) isPresent:(CDVInvokedUrlCommand *)command
{ {
[self isPresent:command type:NotifcationTypeAll]; [self exist:command byType:NotifcationTypeAll];
} }
/** /**
* If a notification by ID is scheduled. * If a notification by ID is scheduled.
* *
* @param id * @param [ Number ]id The ID of the notification.
* The ID of the notification *
* @return [ Void ]
*/ */
- (void) isScheduled:(CDVInvokedUrlCommand*)command - (void) isScheduled:(CDVInvokedUrlCommand*)command
{ {
[self isPresent:command type:NotifcationTypeScheduled]; [self exist:command byType:NotifcationTypeScheduled];
} }
/** /**
* Check if a notification with an ID is triggered. * Check if a notification with an ID is triggered.
* *
* @param id * @param [ Number ]id The ID of the notification.
* The ID of the notification *
* @return [ Void ]
*/ */
- (void) isTriggered:(CDVInvokedUrlCommand*)command - (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 [ APPNotificationType ] type The type of notifications to look for.
* *
* @param type * @return [ Void ]
* The notification life cycle type
*/ */
- (void) isPresent:(CDVInvokedUrlCommand*)command - (void) exist:(CDVInvokedUrlCommand*)command
type:(APPNotificationType)type; byType:(APPNotificationType)type;
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
NSNumber* id = [command argumentAtIndex:0]; NSNumber* id = [command argumentAtIndex:0];
BOOL exist; BOOL exist = [_center notificationExist:id type:type];
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; CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
...@@ -334,197 +281,180 @@ ...@@ -334,197 +281,180 @@
} }
/** /**
* 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. * List of ids for given local notifications.
* *
* @param type * @param [ APPNotificationType ] type The type of notifications to look for.
* Notification life cycle type *
* @param ids * @return [ Void ]
* The IDs of the notifications
*/ */
- (void) getIds:(CDVInvokedUrlCommand*)command - (void) ids:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type; byType:(APPNotificationType)type;
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
NSArray* ids; NSArray* ids = [self.center getNotificationIdsByType:type];
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; CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsArray:ids]; messageAsArray:ids];
[self.commandDelegate sendPluginResult:result [self.commandDelegate sendPluginResult:result
callbackId:command.callbackId]; callbackId:command.callbackId];
}]; }];
} }
/** /**
* 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 [ APPNotificationType ] type The type of notifications to look for.
* *
* @param ids * @return [ Void ]
* The IDs of the notifications
*/ */
- (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 * @param [ Array<Number> ] ids The ids of the notifications to return.
* The IDs of the notifications *
* @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 * @return [ Void ]
* The IDs of the notifications
*/ */
- (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 type * @param [ Array<Number> ] ids The ids of the notifications to return.
* Notification life cycle type *
* @param ids * @return [ Void ]
* The ID of the notification
*/ */
- (void) getOption:(CDVInvokedUrlCommand*)command - (void) triggeredNotifications:(CDVInvokedUrlCommand *)command
byType:(APPNotificationType)type;
{ {
[self.commandDelegate runInBackground:^{ [self notifications:command byType:NotifcationTypeTriggered];
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. * List of notifications by type and id.
*
* @param [ APPNotificationType ] type The type of notifications to look for.
* *
* @param type * @return [ Void ]
* Notification life cycle type
* @param ids
* The IDs of the notifications
*/ */
- (void) getOptions:(CDVInvokedUrlCommand*)command - (void) notifications:(CDVInvokedUrlCommand*)command
byType:(APPNotificationType)type; byType:(APPNotificationType)type;
{ {
[self.commandDelegate runInBackground:^{ [self.commandDelegate runInBackground:^{
NSArray* ids = command.arguments; NSArray* ids = command.arguments;
NSArray* notifications; NSArray* notifications;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { if (type == NotifcationTypeAll && ids.count == 0) {
if (type == NotifcationTypeAll && ids.count == 0) { notifications = [_center getNotificationOptions];
notifications = [self.center getNotificationOptions]; }
} else if (type == NotifcationTypeAll) {
else if (type == NotifcationTypeAll) { notifications = [_center getNotificationOptionsById:ids];
notifications = [self.center getNotificationOptionsById:ids]; }
} else if (ids.count == 0) {
else if (ids.count == 0) { notifications = [_center getNotificationOptionsByType:type];
notifications = [self.center getNotificationOptionsByType:type]; }
} else {
else { notifications = [_center getNotificationOptionsByType:type
notifications = [self.center getNotificationOptionsByType:type andId:ids];
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; CDVPluginResult* result;
...@@ -537,145 +467,89 @@ ...@@ -537,145 +467,89 @@
} }
/** /**
* Inform if the app has the permission to show * Check for permission to show notifications.
* badges and local notifications. *
* @return [ Void ]
*/ */
- (void) hasPermission:(CDVInvokedUrlCommand*)command - (void) check:(CDVInvokedUrlCommand*)command
{ {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { [_center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) {
[self.commandDelegate runInBackground:^{ BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized;
[self.center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings* settings) { BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled;
BOOL authorized = settings.authorizationStatus == UNAuthorizationStatusAuthorized; BOOL permitted = authorized && enabled;
BOOL enabled = settings.notificationCenterSetting == UNNotificationSettingEnabled;
BOOL permitted = authorized && enabled;
CDVPluginResult* result;
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK CDVPluginResult* result;
messageAsBool:permitted]; 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];
[self.commandDelegate sendPluginResult:result [self.commandDelegate sendPluginResult:result
callbackId:command.callbackId]; 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")) { UNAuthorizationOptions options =
[self.commandDelegate runInBackground:^{ (UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
UNAuthorizationOptions options =
(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
[self.center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError* e) { [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 -
#pragma mark Core Logic #pragma mark Private
/** /**
* Schedule the local notification. * Schedule the local notification.
*/ */
- (void) scheduleNotification:(UNMutableNotificationContent*)notification - (void) scheduleNotification:(APPNotificationContent*)notification
{ {
[self.center addNotificationRequest:notification.request __weak APPLocalNotification* weakSelf = self;
withCompletionHandler:^(NSError* e) { UNNotificationRequest* request = notification.request;
[self fireEvent:@"add" notification:notification.request];
}];
}
/** [_center addNotificationRequest:request withCompletionHandler:^(NSError* e) {
* Update the local notification. __strong APPLocalNotification* strongSelf = weakSelf;
*/ [strongSelf fireEvent:@"add" notification:request];
- (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];
//
// [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. // * Update the local notification.
*/ // */
- (void) clearAllNotifications //- (void) updateNotification:(UILocalNotification*)notification
{ // withOptions:(NSDictionary*)newOptions
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) { //{APPNotificationRequest*
[self.center clearAllNotifications]; // NSMutableDictionary* options = [notification.userInfo mutableCopy];
} else { //
[self.app clearAllLocalNotifications]; // [options addEntriesFromDictionary:newOptions];
} // [options setObject:[NSDate date] forKey:@"updatedAt"];
//
[self.app setApplicationIconBadgeNumber:0]; //// notification = [[UILocalNotification alloc]
} //// initWithOptions:options];
////
//// [self scheduleLocalNotification:notification];
//}
#pragma mark - #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 - (void) userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{ {
[self fireEvent:@"trigger" notification:notification.request]; [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 * Called to let your app know which action was selected by the user for a given
* notification. * notification.
...@@ -685,17 +559,18 @@ ...@@ -685,17 +559,18 @@
withCompletionHandler:(void (^)())completionHandler withCompletionHandler:(void (^)())completionHandler
{ {
UNNotificationRequest* notification = response.notification.request; UNNotificationRequest* notification = response.notification.request;
NSString* action = response.actionIdentifier;
[self fireEvent:@"click" notification:notification]; NSString* event = action;
if ([notification.options isRepeating]) { if ([action isEqualToString:UNNotificationDefaultActionIdentifier]) {
[self.center clearNotification:notification]; event = @"click";
[self fireEvent:@"clear" notification:notification]; } else
} else { if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
[self.center cancelNotification:notification]; event = @"clear";
[self fireEvent:@"cancel" notification:notification];
} }
[self fireEvent:event notification:notification];
completionHandler(); completionHandler();
} }
...@@ -708,22 +583,24 @@ ...@@ -708,22 +583,24 @@
- (void) pluginInitialize - (void) pluginInitialize
{ {
eventQueue = [[NSMutableArray alloc] init]; eventQueue = [[NSMutableArray alloc] init];
_app = [UIApplication sharedApplication];
_center = [UNUserNotificationCenter currentNotificationCenter];
self.center.delegate = self; _center.delegate = self;
[_center registerGeneralNotificationCategory];
} }
#pragma mark - #pragma mark -
#pragma mark Helper #pragma mark Helper
/** /**
* Retrieves the application state * Retrieve the state of the application.
* *
* @return * @return "background" or "foreground"
* Either "background" or "foreground"
*/ */
- (NSString*) applicationState - (NSString*) applicationState
{ {
UIApplicationState state = [self.app applicationState]; UIApplicationState state = [_app applicationState];
bool isActive = state == UIApplicationStateActive; bool isActive = state == UIApplicationStateActive;
...@@ -743,23 +620,11 @@ ...@@ -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. * Fire general event.
*
* @param [ NSString* ] event The name of the event to fire.
*
* @return [ Void ]
*/ */
- (void) fireEvent:(NSString*)event - (void) fireEvent:(NSString*)event
{ {
...@@ -767,17 +632,22 @@ ...@@ -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 - (void) fireEvent:(NSString*)event
notification:(UNNotificationRequest*)notification notification:(UNNotificationRequest*)request
{ {
NSString* js; NSString* js;
NSString* appState = [self applicationState]; NSString* appState = [self applicationState];
NSString* params = [NSString stringWithFormat:@"\"%@\"", appState]; NSString* params = [NSString stringWithFormat:@"\"%@\"", appState];
if (notification) { if (request) {
NSString* args = [notification encodeToJSON]; NSString* args = [request encodeToJSON];
params = [NSString stringWithFormat:@"%@,'%@'", args, appState]; params = [NSString stringWithFormat:@"%@,'%@'", args, appState];
} }
...@@ -792,165 +662,4 @@ ...@@ -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 @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
...@@ -20,23 +20,15 @@ ...@@ -20,23 +20,15 @@
* *
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface APPLocalNotificationOptions9 : NSObject #import "APPNotificationOptions.h"
- (id) initWithDict:(NSDictionary*)dict; @import UserNotifications;
@property (readonly, getter=id) NSNumber* id; @interface APPNotificationContent : UNMutableNotificationContent
@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 - (id) initWithOptions:(NSDictionary*)dict;
- (BOOL) isRepeating; - (APPNotificationOptions*) options;
- (UNNotificationRequest*) request;
@end @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 @@ ...@@ -21,39 +21,21 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "APPLocalNotificationOptions.ios9.h" @import UserNotifications;
#ifndef APPNotificationType_DEFINED @interface APPNotificationOptions : NSObject
typedef NS_ENUM(NSUInteger, APPNotificationType) {
NotifcationTypeAll = 0,
NotifcationTypeScheduled = 1,
NotifcationTypeTriggered = 2
};
#endif
@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) initWithDict:(NSDictionary*)dict;
- (id) initWithOptions:(NSDictionary*)dict; - (UNNotificationTrigger*) trigger;
// 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;
@end @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 @@ ...@@ -21,12 +21,14 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "APPNotificationOptions.h"
@import UserNotifications; @import UserNotifications;
@interface UNNotificationRequest (APPLocalNotification) @interface UNNotificationRequest (APPLocalNotification)
// The options provided by the plug-in // The options provided by the plug-in
- (APPLocalNotificationOptions*) options; - (APPNotificationOptions*) options;
// Encode the user info dict to JSON // Encode the user info dict to JSON
- (NSString*) encodeToJSON; - (NSString*) encodeToJSON;
......
...@@ -21,9 +21,9 @@ ...@@ -21,9 +21,9 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "UNMutableNotificationContent+APPLocalNotification.h" #import "APPNotificationOptions.h"
#import "APPLocalNotificationOptions.h"
#import "UNNotificationRequest+APPLocalNotification.h" #import "UNNotificationRequest+APPLocalNotification.h"
#import "APPNotificationContent.h"
#import <objc/runtime.h> #import <objc/runtime.h>
@import UserNotifications; @import UserNotifications;
...@@ -35,7 +35,7 @@ static char optionsKey; ...@@ -35,7 +35,7 @@ static char optionsKey;
/** /**
* Get associated option object * Get associated option object
*/ */
- (APPLocalNotificationOptions*) getOptions - (APPNotificationOptions*) getOptions
{ {
return objc_getAssociatedObject(self, &optionsKey); return objc_getAssociatedObject(self, &optionsKey);
} }
...@@ -43,7 +43,7 @@ static char optionsKey; ...@@ -43,7 +43,7 @@ static char optionsKey;
/** /**
* Set associated option object * Set associated option object
*/ */
- (void) setOptions:(APPLocalNotificationOptions*)options - (void) setOptions:(APPNotificationOptions*)options
{ {
objc_setAssociatedObject(self, &optionsKey, objc_setAssociatedObject(self, &optionsKey,
options, OBJC_ASSOCIATION_RETAIN_NONATOMIC); options, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
...@@ -52,12 +52,12 @@ static char optionsKey; ...@@ -52,12 +52,12 @@ static char optionsKey;
/** /**
* The options provided by the plug-in. * The options provided by the plug-in.
*/ */
- (APPLocalNotificationOptions*) options - (APPNotificationOptions*) options
{ {
APPLocalNotificationOptions* options = [self getOptions]; APPNotificationOptions* options = [self getOptions];
if (!options) { if (!options) {
options = [[APPLocalNotificationOptions alloc] options = [[APPNotificationOptions alloc]
initWithDict:[self.content userInfo]]; initWithDict:[self.content userInfo]];
[self setOptions:options]; [self setOptions:options];
......
...@@ -21,10 +21,12 @@ ...@@ -21,10 +21,12 @@
* @APPPLANT_LICENSE_HEADER_END@ * @APPPLANT_LICENSE_HEADER_END@
*/ */
#import "UNMutableNotificationContent+APPLocalNotification.h" #import "APPNotificationContent.h"
@interface UNUserNotificationCenter (APPLocalNotification) @interface UNUserNotificationCenter (APPLocalNotification)
extern NSString * const kAPPGeneralCategory;
typedef NS_ENUM(NSUInteger, APPNotificationType) { typedef NS_ENUM(NSUInteger, APPNotificationType) {
NotifcationTypeAll = 0, NotifcationTypeAll = 0,
NotifcationTypeScheduled = 1, NotifcationTypeScheduled = 1,
...@@ -36,6 +38,8 @@ typedef NS_ENUM(NSUInteger, APPNotificationType) { ...@@ -36,6 +38,8 @@ typedef NS_ENUM(NSUInteger, APPNotificationType) {
@property (readonly, getter=getNotifications) NSArray* localNotifications; @property (readonly, getter=getNotifications) NSArray* localNotifications;
@property (readonly, getter=getNotificationIds) NSArray* localNotificationIds; @property (readonly, getter=getNotificationIds) NSArray* localNotificationIds;
- (void) registerGeneralNotificationCategory;
// List of all notification IDs from given type // List of all notification IDs from given type
- (NSArray*) getNotificationIdsByType:(APPNotificationType)type; - (NSArray*) getNotificationIdsByType:(APPNotificationType)type;
......
...@@ -26,9 +26,32 @@ ...@@ -26,9 +26,32 @@
@import UserNotifications; @import UserNotifications;
NSString * const kAPPGeneralCategory = @"GENERAL";
@implementation UNUserNotificationCenter (APPLocalNotification) @implementation UNUserNotificationCenter (APPLocalNotification)
#pragma mark - #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 #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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * Version 2.0 (the 'License'). You may not use this file except in
...@@ -17,56 +13,60 @@ ...@@ -17,56 +13,60 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
var exec = require('cordova/exec'); 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 () { exports.hasPermission = function (callback, scope) {
return this._defaults; 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) { exports.requestPermission = function (callback, scope) {
var defaults = this.getDefaults(); var fn = this.createCallbackFn(callback, scope);
for (var key in defaults) { if (device.platform != 'iOS') {
if (newDefaults.hasOwnProperty(key)) { fn(true);
defaults[key] = newDefaults[key]; return;
}
} }
exec(fn, null, 'LocalNotification', 'request', []);
}; };
/** /**
* Schedule a new local notification. * Schedule notifications.
* *
* @param {Object} msgs * @param [ Array ] notifications The notifications to schedule.
* The notification properties * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been canceled * @param [ Object ] args Optional flags how to schedule.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/ */
exports.schedule = function (msgs, callback, scope, args) { exports.schedule = function (msgs, callback, scope, args) {
var fn = function(granted) { var fn = function (granted) {
if (!granted) return; if (!granted) return;
...@@ -85,55 +85,54 @@ exports.schedule = function (msgs, callback, scope, args) { ...@@ -85,55 +85,54 @@ exports.schedule = function (msgs, callback, scope, args) {
if (args && args.skipPermission) { if (args && args.skipPermission) {
fn.call(this, true); fn.call(this, true);
} else { } else {
this.registerPermission(fn, this); this.requestPermission(fn, this);
} }
}; };
/** // /**
* Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
* // *
* @param {Object} notifications // * @param {Object} notifications
* The notification properties to update // * The notification properties to update
* @param {Function} callback // * @param {Function} callback
* A function to be called after the notification has been updated // * A function to be called after the notification has been updated
* @param {Object?} scope // * @param {Object?} scope
* The scope for the callback function // * The scope for the callback function
* @param {Object?} args // * @param {Object?} args
* skipPermission:true schedules the notifications immediatly without // * skipPermission:true schedules the notifications immediatly without
* registering or checking for permission // * registering or checking for permission
*/ // */
exports.update = function (msgs, callback, scope, args) { // exports.update = function (msgs, callback, scope, args) {
var fn = function(granted) { // 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++) { // for (var i = 0; i < notifications.length; i++) {
var notification = notifications[i]; // var notification = notifications[i];
this.convertProperties(notification); // this.convertProperties(notification);
} // }
this.exec('update', notifications, callback, scope); // this.exec('update', notifications, callback, scope);
}; // };
if (args && args.skipPermission) { // if (args && args.skipPermission) {
fn.call(this, true); // fn.call(this, true);
} else { // } else {
this.registerPermission(fn, this); // this.registerPermission(fn, this);
} // }
}; // };
/** /**
* Clear the specified notification. * Clear the specified notifications by id.
* *
* @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been cleared *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.clear = function (ids, callback, scope) { exports.clear = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids]; ids = Array.isArray(ids) ? ids : [ids];
...@@ -143,26 +142,25 @@ exports.clear = function (ids, callback, scope) { ...@@ -143,26 +142,25 @@ exports.clear = function (ids, callback, scope) {
}; };
/** /**
* Clear all previously sheduled notifications. * Clear all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
this.exec('clearAll', null, callback, scope); this.exec('clearAll', null, callback, scope);
}; };
/** /**
* Cancel the specified notifications. * Clear the specified notifications by id.
* *
* @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notifications has been canceled *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.cancel = function (ids, callback, scope) { exports.cancel = function (ids, callback, scope) {
ids = Array.isArray(ids) ? ids : [ids]; ids = Array.isArray(ids) ? ids : [ids];
...@@ -172,69 +170,66 @@ exports.cancel = function (ids, callback, scope) { ...@@ -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 * @return [ Void ]
* 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) { exports.cancelAll = function (callback, scope) {
this.exec('cancelAll', null, callback, scope); this.exec('cancelAll', null, callback, scope);
}; };
/** /**
* Check if a notification with an ID is present. * Check if a notification is present.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isPresent = function (id, callback, scope) { 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. * Check if a notification is scheduled.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isScheduled = function (id, callback, scope) { 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. * Check if a notification was triggered.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isTriggered = function (id, callback, scope) { 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 The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* *
* @param {Function} callback * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllIds = function (callback, scope) { exports.getAllIds = function (callback, scope) {
this.exec('getAllIds', null, callback, scope); this.exec('ids', null, callback, scope);
}; };
/** /**
...@@ -245,39 +240,38 @@ exports.getIds = function () { ...@@ -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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getScheduledIds = function (callback, scope) { 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getTriggeredIds = function (callback, scope) { 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.get = function () { exports.get = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -291,37 +285,36 @@ exports.get = function () { ...@@ -291,37 +285,36 @@ exports.get = function () {
scope = args[2]; scope = args[2];
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingle', Number(ids), callback, scope); this.exec('notification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getAll = function (callback, scope) { 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getScheduled = function () { exports.getScheduled = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -339,37 +332,34 @@ exports.getScheduled = function () { ...@@ -339,37 +332,34 @@ exports.getScheduled = function () {
} }
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingleScheduled', Number(ids), callback, scope); this.exec('scheduledNotification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllScheduled = function (callback, 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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getTriggered = function () { exports.getTriggered = function () {
var args = Array.apply(null, arguments); var args = Array.apply(null, arguments);
...@@ -387,86 +377,59 @@ exports.getTriggered = function () { ...@@ -387,86 +377,59 @@ exports.getTriggered = function () {
} }
if (!Array.isArray(ids)) { if (!Array.isArray(ids)) {
this.exec('getSingleTriggered', Number(ids), callback, scope); this.exec('triggeredNotification', Number(ids), callback, scope);
return; return;
} }
ids = this.convertIds(ids); 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 * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllTriggered = function (callback, 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 * @return [ Object ]
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
*/ */
exports.hasPermission = function (callback, scope) { exports.getDefaults = function () {
var fn = this.createCallbackFn(callback, scope); return this._defaults;
if (device.platform != 'iOS') {
fn(true);
return;
}
exec(fn, null, 'LocalNotification', 'check', []);
}; };
/** /**
* Register permission to show notifications if not already granted. * Overwrite default settings.
* *
* @param {Function} callback * @param [ Object ] newDefaults New default values.
* The function to be exec as the callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
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;
}
var fn = this.createCallbackFn(callback, scope);
if (device.platform != 'iOS') { for (var key in defaults) {
fn(true); if (newDefaults.hasOwnProperty(key)) {
return; defaults[key] = newDefaults[key];
}
} }
exec(fn, null, 'LocalNotification', 'request', []);
}; };
/**********
* EVENTS *
**********/
/** /**
* Register callback for given event. * Register callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* The function to be exec as callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
exports.on = function (event, callback, scope) { exports.on = function (event, callback, scope) {
...@@ -485,10 +448,10 @@ exports.on = function (event, callback, scope) { ...@@ -485,10 +448,10 @@ exports.on = function (event, callback, scope) {
/** /**
* Unregister callback for given event. * Unregister callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback *
* The function to be exec as callback * @return [ Void ]
*/ */
exports.un = function (event, callback) { exports.un = function (event, callback) {
var listener = this._listener[event]; 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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * Version 2.0 (the 'License'). You may not use this file except in
...@@ -17,18 +13,11 @@ ...@@ -17,18 +13,11 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
var exec = require('cordova/exec'), var exec = require('cordova/exec'),
channel = require('cordova/channel'); channel = require('cordova/channel');
/***********
* MEMBERS *
***********/
// Default values // Default values
exports._defaults = { exports._defaults = {
text: '', text: '',
...@@ -41,48 +30,38 @@ exports._defaults = { ...@@ -41,48 +30,38 @@ exports._defaults = {
at: undefined at: undefined
}; };
// listener // Listener
exports._listener = {}; exports._listener = {};
// Registered permission flag
exports._registered = false;
/********
* UTIL *
********/
/** /**
* Merge platform specific properties into the default ones. * Merge platform specific properties into the default ones.
* *
* @return {Object} * @return [ Void ]
* The default properties for the platform
*/ */
exports.applyPlatformSpecificOptions = function () { exports.applyPlatformSpecificOptions = function () {
var defaults = this._defaults; var defaults = this._defaults;
switch (device.platform) { switch (device.platform) {
case 'Android': case 'Android':
defaults.icon = 'res://ic_popup_reminder'; defaults.icon = 'res://ic_popup_reminder';
defaults.smallIcon = undefined; defaults.smallIcon = undefined;
defaults.ongoing = false; defaults.ongoing = false;
defaults.autoClear = true; defaults.autoClear = true;
defaults.led = undefined; defaults.led = undefined;
defaults.color = undefined; defaults.color = undefined;
break;
case 'iOS':
defaults.attachments = undefined;
break; break;
} }
return defaults;
}; };
/** /**
* Merge custom properties with the default values. * Merge custom properties with the default values.
* *
* @param {Object} options * @param [ Object ] options Set of custom values.
* Set of custom values
* *
* @retrun {Object} * @retrun [ Object ]
* The merged property list
*/ */
exports.mergeWithDefaults = function (options) { exports.mergeWithDefaults = function (options) {
var defaults = this.getDefaults(); var defaults = this.getDefaults();
...@@ -126,11 +105,9 @@ exports.mergeWithDefaults = function (options) { ...@@ -126,11 +105,9 @@ exports.mergeWithDefaults = function (options) {
/** /**
* Convert the passed values to their required type. * Convert the passed values to their required type.
* *
* @param {Object} options * @param [ Object ] options Properties to convert for.
* Set of custom values
* *
* @retrun {Object} * @return [ Object ] The converted property list
* The converted property list
*/ */
exports.convertProperties = function (options) { exports.convertProperties = function (options) {
...@@ -172,46 +149,33 @@ exports.convertProperties = function (options) { ...@@ -172,46 +149,33 @@ exports.convertProperties = function (options) {
options.data = JSON.stringify(options.data); 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; 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 * @param [ Function ] fn The function to be exec as the callback.
* The callback function * @param [ Object ] scope The callback function's scope.
* @param {Object} scope
* The scope for the function
* *
* @return {Function} * @return [ Function ]
* The new callback function
*/ */
exports.createCallbackFn = function (callbackFn, scope) { exports.createCallbackFn = function (fn, scope) {
if (typeof callbackFn != 'function') if (typeof fn != 'function')
return; return;
return function () { return function () {
callbackFn.apply(scope || this, arguments); fn.apply(scope || this, arguments);
}; };
}; };
/** /**
* Convert the IDs to numbers. * Convert the IDs to numbers.
* *
* @param {String/Number[]} ids * @param [ Array ] ids
* *
* @return Array of Numbers * @return [ Array<Number> ]
*/ */
exports.convertIds = function (ids) { exports.convertIds = function (ids) {
var convertedIds = []; var convertedIds = [];
...@@ -226,10 +190,10 @@ exports.convertIds = function (ids) { ...@@ -226,10 +190,10 @@ exports.convertIds = function (ids) {
/** /**
* First found value for the given keys. * First found value for the given keys.
* *
* @param {Object} options * @param [ Object ] options Object with key-value properties.
* Object with key-value properties * @param [ *Array<String> ] keys List of keys.
* @param {String[]} keys* *
* Key list * @return [ Object ]
*/ */
exports.getValueFor = function (options) { exports.getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1); var keys = Array.apply(null, arguments).slice(1);
...@@ -244,12 +208,12 @@ exports.getValueFor = function (options) { ...@@ -244,12 +208,12 @@ exports.getValueFor = function (options) {
}; };
/** /**
* Fire event with given arguments. * Fire the event with given arguments.
* *
* @param {String} event * @param [ String ] event The event's name.
* The event's name * @param [ *Array] args The callback's arguments.
* @param {args*} *
* The callback's arguments * @return [ Void]
*/ */
exports.fireEvent = function (event) { exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1), var args = Array.apply(null, arguments).slice(1),
...@@ -269,14 +233,12 @@ exports.fireEvent = function (event) { ...@@ -269,14 +233,12 @@ exports.fireEvent = function (event) {
/** /**
* Execute the native counterpart. * Execute the native counterpart.
* *
* @param {String} action * @param [ String ] action The name of the action.
* The name of the action * @param [ Array ] args Array of arguments.
* @param args[] * @param [ Function] callback The callback function.
* Array of arguments * @param [ Object ] scope The scope for the function.
* @param {Function} callback *
* The callback function * @return [ Void ]
* @param {Object} scope
* The scope for the function
*/ */
exports.exec = function (action, args, callback, scope) { exports.exec = function (action, args, callback, scope) {
var fn = this.createCallbackFn(callback, scope), var fn = this.createCallbackFn(callback, scope),
...@@ -291,11 +253,6 @@ exports.exec = function (action, args, callback, scope) { ...@@ -291,11 +253,6 @@ exports.exec = function (action, args, callback, scope) {
exec(fn, null, 'LocalNotification', action, params); exec(fn, null, 'LocalNotification', action, params);
}; };
/*********
* HOOKS *
*********/
// Called after 'deviceready' event // Called after 'deviceready' event
channel.deviceready.subscribe(function () { channel.deviceready.subscribe(function () {
// Device is ready now, the listeners are registered // 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 * This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License * as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in * Version 2.0 (the 'License'). You may not use this file except in
...@@ -17,192 +13,159 @@ ...@@ -17,192 +13,159 @@
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and * Please see the License for the specific language governing rights and
* limitations under the License. * limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/ */
/*************
* INTERFACE *
*************/
/** /**
* Returns the default settings. * Request permission to show notifications.
* *
* @return {Object} * @param [ Function ] callback The function to be exec as the callback.
*/ * @param [ Object ] scope The callback function's scope.
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 * @return [ Void ]
* The function to be exec as the callback
* @param {Object?} scope
* The callback function's scope
*/ */
exports.hasPermission = function (callback, scope) { exports.hasPermission = function (callback, scope) {
this.core.hasPermission(callback, scope); this.core.hasPermission(callback, scope);
}; };
/** /**
* Register permission to show notifications if not already granted. * Request permission to show notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* The function to be exec as the callback * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The callback function's scope * @return [ Void ]
*/ */
exports.requestPermission = function (callback, scope) { exports.requestPermission = function (callback, scope) {
this.core.requestPermission(callback, scope); this.core.requestPermission(callback, scope);
}; };
/** /**
* Schedule a new local notification. * Schedule notifications.
* *
* @param {Object} notifications * @param [ Array ] notifications The notifications to schedule.
* The notification properties * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been canceled * @param [ Object ] args Optional flags how to schedule.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
* @param {Object?} args
* skipPermission:true schedules the notifications immediatly without
* registering or checking for permission
*/ */
exports.schedule = function (notifications, callback, scope, args) { exports.schedule = function (notifications, callback, scope, args) {
this.core.schedule(notifications, callback, scope, args); this.core.schedule(notifications, callback, scope, args);
}; };
/** // /**
* Update existing notifications specified by IDs in options. // * Update existing notifications specified by IDs in options.
* // *
* @param {Object} notifications // * @param {Object} notifications
* The notification properties to update // * The notification properties to update
* @param {Function} callback // * @param {Function} callback
* A function to be called after the notification has been updated // * A function to be called after the notification has been updated
* @param {Object?} scope // * @param {Object?} scope
* The scope for the callback function // * The scope for the callback function
* @param {Object?} args // * @param {Object?} args
* skipPermission:true schedules the notifications immediatly without // * skipPermission:true schedules the notifications immediatly without
* registering or checking for permission // * registering or checking for permission
*/ // */
exports.update = function (notifications, callback, scope, args) { // exports.update = function (notifications, callback, scope, args) {
this.core.update(notifications, callback, scope, args); // this.core.update(notifications, callback, scope, args);
}; // };
/** /**
* Clear the specified notification. * Clear the specified notifications by id.
* *
* @param {String} id * @param [ Array<Int> ] ids The IDs of the notifications.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notification has been cleared *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.clear = function (ids, callback, scope) { exports.clear = function (ids, callback, scope) {
this.core.clear(ids, callback, scope); this.core.clear(ids, callback, scope);
}; };
/** /**
* Clear all previously sheduled notifications. * Clear all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been cleared * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.clearAll = function (callback, scope) { exports.clearAll = function (callback, scope) {
this.core.clearAll(callback, scope); this.core.clearAll(callback, scope);
}; };
/** /**
* Cancel the specified notifications. * Cancel the specified notifications by id.
* *
* @param {String[]} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* The IDs of the notifications * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A function to be called after the notifications has been canceled *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.cancel = function (ids, callback, scope) { exports.cancel = function (ids, callback, scope) {
this.core.cancel(ids, callback, scope); this.core.cancel(ids, callback, scope);
}; };
/** /**
* Remove all previously registered notifications. * Cancel all scheduled notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A function to be called after all notifications have been canceled * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.cancelAll = function (callback, scope) { exports.cancelAll = function (callback, scope) {
this.core.cancelAll(callback, scope); this.core.cancelAll(callback, scope);
}; };
/** /**
* Check if a notification with an ID is present. * Check if a notification is present.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isPresent = function (id, callback, scope) { exports.isPresent = function (id, callback, scope) {
this.core.isPresent(id, callback, scope); this.core.isPresent(id, callback, scope);
}; };
/** /**
* Check if a notification with an ID is scheduled. * Check if a notification is scheduled.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isScheduled = function (id, callback, scope) { exports.isScheduled = function (id, callback, scope) {
this.core.isScheduled(id, callback, scope); this.core.isScheduled(id, callback, scope);
}; };
/** /**
* Check if a notification with an ID was triggered. * Check if a notification was triggered.
* *
* @param {String} id * @param [ Int ] id The ID of the notification.
* The ID of the notification * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.isTriggered = function (id, callback, scope) { exports.isTriggered = function (id, callback, scope) {
this.core.isTriggered(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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllIds = function (callback, scope) { exports.getAllIds = function (callback, scope) {
this.core.getAllIds(callback, scope); this.core.getAllIds(callback, scope);
...@@ -216,148 +179,131 @@ exports.getIds = function () { ...@@ -216,148 +179,131 @@ exports.getIds = function () {
}; };
/** /**
* List all scheduled notification IDs. * List of all scheduled notification IDs.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope *
* The scope for the callback function * @return [ Void ]
*/ */
exports.getScheduledIds = function (callback, scope) { exports.getScheduledIds = function (callback, scope) {
this.core.getScheduledIds(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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getTriggeredIds = function (callback, scope) { exports.getTriggeredIds = function (callback, scope) {
this.core.getTriggeredIds(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.get = function () { exports.get = function (ids, callback, scope) {
this.core.get.apply(this.core, arguments); 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 * @return [ Void ]
* A callback function to be called with the list
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAll = function (callback, scope) { exports.getAll = function (callback, scope) {
this.core.getAll(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getScheduled = function () { exports.getScheduled = function (ids, callback, scope) {
this.core.getScheduled.apply(this.core, arguments); this.core.getScheduled(ids, callback, scope);
}; };
/** /**
* Property list for all scheduled notifications. * List of all scheduled notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllScheduled = function (callback, scope) { exports.getAllScheduled = function (callback, scope) {
this.core.getAllScheduled(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. * If called without IDs, all notification will be returned.
* *
* @param {Number[]?} ids * @param [ Array<Int> ] ids The IDs of the notifications.
* Set of notification IDs * @param [ Function ] callback The function to be exec as the callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* A callback function to be called with the list *
* @param {Object?} scope * @return [ Void ]
* The scope for the callback function
*/ */
exports.getTriggered = function () { exports.getTriggered = function (ids, callback, scope) {
this.core.getTriggered.apply(this.core, arguments); this.core.getTriggered(ids, callback, scope);
}; };
/** /**
* Property list for all triggered notifications. * List of all triggered notifications.
* *
* @param {Function} callback * @param [ Function ] callback The function to be exec as the callback.
* A callback function to be called with the list * @param [ Object ] scope The callback function's scope.
* @param {Object?} scope
* The scope for the callback function
*/ */
exports.getAllTriggered = function (callback, scope) { exports.getAllTriggered = function (callback, scope) {
this.core.getAllTriggered(callback, scope); this.core.getAllTriggered(callback, scope);
}; };
/****************
* DEPRECATIONS *
****************/
/** /**
* Schedule a new local notification. * The (platform specific) default settings.
*
* @return [ Object ]
*/ */
exports.add = function () { exports.getDefaults = function () {
console.warn('Depreated: Please use `notification.local.schedule` instead.'); return this.core.getDefaults();
this.schedule.apply(this, arguments);
}; };
/** /**
* Register permission to show notifications * Overwrite default settings.
* if not already granted. *
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/ */
exports.promptForPermission = function () { exports.setDefaults = function (defaults) {
console.warn('Depreated: Please use `notification.local.registerPermission` instead.'); this.core.setDefaults(defaults);
this.registerPermission.apply(this, arguments);
}; };
/**********
* EVENTS *
**********/
/** /**
* Register callback for given event. * Register callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback * @param [ Object ] scope The callback function's scope.
* The function to be exec as callback *
* @param {Object?} scope * @return [ Void ]
* The callback function's scope
*/ */
exports.on = function (event, callback, scope) { exports.on = function (event, callback, scope) {
this.core.on(event, callback, scope); this.core.on(event, callback, scope);
...@@ -366,10 +312,10 @@ exports.on = function (event, callback, scope) { ...@@ -366,10 +312,10 @@ exports.on = function (event, callback, scope) {
/** /**
* Unregister callback for given event. * Unregister callback for given event.
* *
* @param {String} event * @param [ String ] event The name of the event.
* The event's name * @param [ Function ] callback The function to be exec as callback.
* @param {Function} callback *
* The function to be exec as callback * @return [ Void ]
*/ */
exports.un = function (event, callback) { exports.un = function (event, callback) {
this.core.un(event, callback); this.core.un(event, callback);
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
<body> <body>
<div> <div>
<div class="app"> <div class="app">
<h1>Local Notification Example</h1> <h1>Notification Example</h1>
<div id="deviceready" class="blink"> <div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p> <p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p> <p class="event received">Device is Ready</p>
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
<a id="sched_multi" class="button orange">Multiple</a> <a id="sched_multi" class="button orange">Multiple</a>
</div> </div>
<div class="container"> <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> <a id="sched_interval" class="button orange">Interval</a>
</div> </div>
<h2 class="section">Update</h2> <h2 class="section">Update</h2>
...@@ -85,7 +85,7 @@ ...@@ -85,7 +85,7 @@
<a id="triggered_ids" class="button grey">Triggered</a> <a id="triggered_ids" class="button grey">Triggered</a>
</div> </div>
<div class="container"> <div class="container">
<a id="all_ids" class="button grey">All</a> <a id="ids" class="button grey">All</a>
</div> </div>
<h2 class="section">Notifications</h2> <h2 class="section">Notifications</h2>
<div class="container"> <div class="container">
...@@ -93,11 +93,11 @@ ...@@ -93,11 +93,11 @@
<a id="triggered_nots" class="button grey">Triggered</a> <a id="triggered_nots" class="button grey">Triggered</a>
</div> </div>
<div class="container"> <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> <a id="multiple_nots" class="button grey">Multiple</a>
</div> </div>
<div class="container"> <div class="container">
<a id="all_nots" class="button grey">All</a> <a id="notifications" class="button grey">All</a>
</div> </div>
<h2 class="section">Defaults</h2> <h2 class="section">Defaults</h2>
<div class="container"> <div class="container">
......
...@@ -36,6 +36,7 @@ var app = { ...@@ -36,6 +36,7 @@ var app = {
onDeviceReady: function() { onDeviceReady: function() {
app.receivedEvent('deviceready'); app.receivedEvent('deviceready');
app.pluginInitialize(); app.pluginInitialize();
app.bindNotificationEvents();
}, },
// Update DOM on a Received Event // Update DOM on a Received Event
receivedEvent: function(id) { receivedEvent: function(id) {
...@@ -50,16 +51,240 @@ var app = { ...@@ -50,16 +51,240 @@ var app = {
}, },
// Initialize plugin // Initialize plugin
pluginInitialize: function() { pluginInitialize: function() {
document.getElementById('granted').onclick = app.hasPermission; document.getElementById('granted').onclick = app.hasPermission;
document.getElementById('request').onclick = app.askPermission; 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 // Check permissions to read accounts
hasPermission: function () { hasPermission: function () {
cordova.plugins.notification.local.hasPermission(showToast); cordova.plugins.notification.local.hasPermission(function (granted) {
showToast(granted ? 'Yes' : 'No');
});
}, },
// Request permissions to read accounts // Request permissions to read accounts
askPermission: function () { 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