PageRenderTime 44ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/front/plugins/phonegap-plugin-push/src/ios/PushPlugin.m

https://gitlab.com/boxnia/NFU_MOVIL
Objective C | 611 lines | 466 code | 95 blank | 50 comment | 119 complexity | 92ae6d26adca68aea5cabfcb618cc76c MD5 | raw file
  1. /*
  2. Copyright 2009-2011 Urban Airship Inc. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. 1. Redistributions of source code must retain the above copyright notice, this
  6. list of conditions and the following disclaimer.
  7. 2. Redistributions in binaryform must reproduce the above copyright notice,
  8. this list of conditions and the following disclaimer in the documentation
  9. and/or other materials provided withthe distribution.
  10. THIS SOFTWARE IS PROVIDED BY THE URBAN AIRSHIP INC``AS IS'' AND ANY EXPRESS OR
  11. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  12. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  13. EVENT SHALL URBAN AIRSHIP INC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  14. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  15. BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  16. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  17. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  18. OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  19. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  20. */
  21. // See GGLInstanceID.h
  22. #define GMP_NO_MODULES true
  23. #import "PushPlugin.h"
  24. #import "CloudMessaging.h"
  25. @implementation PushPlugin : CDVPlugin
  26. @synthesize notificationMessage;
  27. @synthesize isInline;
  28. @synthesize coldstart;
  29. @synthesize callbackId;
  30. @synthesize notificationCallbackId;
  31. @synthesize callback;
  32. @synthesize clearBadge;
  33. @synthesize handlerObj;
  34. @synthesize usesGCM;
  35. @synthesize gcmSandbox;
  36. @synthesize gcmSenderId;
  37. @synthesize gcmRegistrationOptions;
  38. @synthesize gcmRegistrationHandler;
  39. @synthesize gcmRegistrationToken;
  40. @synthesize gcmTopics;
  41. -(void)initGCMRegistrationHandler;
  42. {
  43. __weak __block PushPlugin *weakSelf = self;
  44. gcmRegistrationHandler = ^(NSString *registrationToken, NSError *error){
  45. if (registrationToken != nil) {
  46. NSLog(@"GCM Registration Token: %@", registrationToken);
  47. [weakSelf setGcmRegistrationToken: registrationToken];
  48. id topics = [weakSelf gcmTopics];
  49. if (topics != nil) {
  50. for (NSString *topic in topics) {
  51. NSLog(@"subscribe from topic: %@", topic);
  52. id pubSub = [GCMPubSub sharedInstance];
  53. [pubSub subscribeWithToken: [weakSelf gcmRegistrationToken]
  54. topic:[NSString stringWithFormat:@"/topics/%@", topic]
  55. options:nil
  56. handler:^void(NSError *error) {
  57. if (error) {
  58. if (error.code == 3001) {
  59. NSLog(@"Already subscribed to %@", topic);
  60. } else {
  61. NSLog(@"Failed to subscribe to topic %@: %@", topic, error);
  62. }
  63. }
  64. else {
  65. NSLog(@"Successfully subscribe to topic %@", topic);
  66. }
  67. }];
  68. }
  69. }
  70. [weakSelf registerWithToken:registrationToken];
  71. } else {
  72. NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);
  73. [weakSelf failWithMessage:@"" withError:error];
  74. }
  75. };
  76. }
  77. // GCM refresh token
  78. // Unclear how this is testable under normal circumstances
  79. - (void)onTokenRefresh {
  80. #if !TARGET_IPHONE_SIMULATOR
  81. // A rotation of the registration tokens is happening, so the app needs to request a new token.
  82. NSLog(@"The GCM registration token needs to be changed.");
  83. [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:[self gcmSenderId]
  84. scope:kGGLInstanceIDScopeGCM
  85. options:[self gcmRegistrationOptions]
  86. handler:[self gcmRegistrationHandler]];
  87. #endif
  88. }
  89. - (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error {
  90. NSLog(@"willSendDataMessageWithID");
  91. if (error) {
  92. // Failed to send the message.
  93. } else {
  94. // Will send message, you can save the messageID to track the message
  95. }
  96. }
  97. - (void)didSendDataMessageWithID:(NSString *)messageID {
  98. NSLog(@"willSendDataMessageWithID");
  99. // Did successfully send message identified by messageID
  100. }
  101. - (void)didDeleteMessagesOnServer {
  102. NSLog(@"didDeleteMessagesOnServer");
  103. // Some messages sent to this device were deleted on the GCM server before reception, likely
  104. // because the TTL expired. The client should notify the app server of this, so that the app
  105. // server can resend those messages.
  106. }
  107. - (void)unregister:(CDVInvokedUrlCommand*)command;
  108. {
  109. self.callbackId = command.callbackId;
  110. NSArray* topics = [command argumentAtIndex:0];
  111. if (topics != nil) {
  112. id pubSub = [GCMPubSub sharedInstance];
  113. for (NSString *topic in topics) {
  114. NSLog(@"unsubscribe from topic: %@", topic);
  115. [pubSub unsubscribeWithToken: [self gcmRegistrationToken]
  116. topic:topic
  117. options:nil
  118. handler:^void(NSError *error) {
  119. if (error) {
  120. NSLog(@"Failed to unsubscribe from topic %@: %@", topic, error);
  121. }
  122. else {
  123. NSLog(@"Successfully unsubscribe from topic %@", topic);
  124. }
  125. }];
  126. }
  127. } else {
  128. [[UIApplication sharedApplication] unregisterForRemoteNotifications];
  129. [self successWithMessage:@"unregistered"];
  130. }
  131. }
  132. - (void)init:(CDVInvokedUrlCommand*)command;
  133. {
  134. [self.commandDelegate runInBackground:^ {
  135. NSLog(@"Push Plugin register called");
  136. self.callbackId = command.callbackId;
  137. NSMutableDictionary* options = [command.arguments objectAtIndex:0];
  138. NSMutableDictionary* iosOptions = [options objectForKey:@"ios"];
  139. NSArray* topics = [iosOptions objectForKey:@"topics"];
  140. [self setGcmTopics:topics];
  141. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  142. UIUserNotificationType UserNotificationTypes = UIUserNotificationTypeNone;
  143. #endif
  144. UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeNone;
  145. id badgeArg = [iosOptions objectForKey:@"badge"];
  146. id soundArg = [iosOptions objectForKey:@"sound"];
  147. id alertArg = [iosOptions objectForKey:@"alert"];
  148. id clearBadgeArg = [iosOptions objectForKey:@"clearBadge"];
  149. if (([badgeArg isKindOfClass:[NSString class]] && [badgeArg isEqualToString:@"true"]) || [badgeArg boolValue])
  150. {
  151. notificationTypes |= UIRemoteNotificationTypeBadge;
  152. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  153. UserNotificationTypes |= UIUserNotificationTypeBadge;
  154. #endif
  155. }
  156. if (([soundArg isKindOfClass:[NSString class]] && [soundArg isEqualToString:@"true"]) || [soundArg boolValue])
  157. {
  158. notificationTypes |= UIRemoteNotificationTypeSound;
  159. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  160. UserNotificationTypes |= UIUserNotificationTypeSound;
  161. #endif
  162. }
  163. if (([alertArg isKindOfClass:[NSString class]] && [alertArg isEqualToString:@"true"]) || [alertArg boolValue])
  164. {
  165. notificationTypes |= UIRemoteNotificationTypeAlert;
  166. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  167. UserNotificationTypes |= UIUserNotificationTypeAlert;
  168. #endif
  169. }
  170. notificationTypes |= UIRemoteNotificationTypeNewsstandContentAvailability;
  171. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  172. UserNotificationTypes |= UIUserNotificationActivationModeBackground;
  173. #endif
  174. if (clearBadgeArg == nil || ([clearBadgeArg isKindOfClass:[NSString class]] && [clearBadgeArg isEqualToString:@"false"]) || ![clearBadgeArg boolValue]) {
  175. NSLog(@"PushPlugin.register: setting badge to false");
  176. clearBadge = NO;
  177. } else {
  178. NSLog(@"PushPlugin.register: setting badge to true");
  179. clearBadge = YES;
  180. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  181. }
  182. NSLog(@"PushPlugin.register: clear badge is set to %d", clearBadge);
  183. if (notificationTypes == UIRemoteNotificationTypeNone)
  184. NSLog(@"PushPlugin.register: Push notification type is set to none");
  185. isInline = NO;
  186. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  187. NSLog(@"PushPlugin.register: better button setup");
  188. // setup action buttons
  189. NSMutableSet *categories = [[NSMutableSet alloc] init];
  190. id categoryOptions = [iosOptions objectForKey:@"categories"];
  191. if (categoryOptions != nil && [categoryOptions isKindOfClass:[NSDictionary class]]) {
  192. for (id key in categoryOptions) {
  193. NSLog(@"categories: key %@", key);
  194. id category = [categoryOptions objectForKey:key];
  195. id yesButton = [category objectForKey:@"yes"];
  196. UIMutableUserNotificationAction *yesAction;
  197. if (yesButton != nil && [yesButton isKindOfClass:[NSDictionary class]]) {
  198. yesAction = [self createAction: yesButton];
  199. }
  200. id noButton = [category objectForKey:@"no"];
  201. UIMutableUserNotificationAction *noAction;
  202. if (noButton != nil && [noButton isKindOfClass:[NSDictionary class]]) {
  203. noAction = [self createAction: noButton];
  204. }
  205. id maybeButton = [category objectForKey:@"maybe"];
  206. UIMutableUserNotificationAction *maybeAction;
  207. if (maybeButton != nil && [maybeButton isKindOfClass:[NSDictionary class]]) {
  208. maybeAction = [self createAction: maybeButton];
  209. }
  210. // First create the category
  211. UIMutableUserNotificationCategory *notificationCategory = [[UIMutableUserNotificationCategory alloc] init];
  212. // Identifier to include in your push payload and local notification
  213. notificationCategory.identifier = key;
  214. NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
  215. NSMutableArray *minimalCategoryArray = [[NSMutableArray alloc] init];
  216. if (yesButton != nil) {
  217. [categoryArray addObject:yesAction];
  218. [minimalCategoryArray addObject:yesAction];
  219. }
  220. if (noButton != nil) {
  221. [categoryArray addObject:noAction];
  222. [minimalCategoryArray addObject:noAction];
  223. }
  224. if (maybeButton != nil) {
  225. [categoryArray addObject:maybeAction];
  226. }
  227. // Add the actions to the category and set the action context
  228. [notificationCategory setActions:categoryArray forContext:UIUserNotificationActionContextDefault];
  229. // Set the actions to present in a minimal context
  230. [notificationCategory setActions:minimalCategoryArray forContext:UIUserNotificationActionContextMinimal];
  231. NSLog(@"Adding category %@", key);
  232. [categories addObject:notificationCategory];
  233. }
  234. }
  235. #else
  236. NSLog(@"PushPlugin.register: action buttons only supported on iOS8 and above");
  237. #endif
  238. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
  239. if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  240. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UserNotificationTypes categories:categories];
  241. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  242. [[UIApplication sharedApplication] registerForRemoteNotifications];
  243. } else {
  244. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
  245. (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
  246. }
  247. #else
  248. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
  249. (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
  250. #endif
  251. // GCM options
  252. [self setGcmSenderId: [iosOptions objectForKey:@"senderID"]];
  253. NSLog(@"GCM Sender ID %@", gcmSenderId);
  254. if([[self gcmSenderId] length] > 0) {
  255. NSLog(@"Using GCM Notification");
  256. [self setUsesGCM: YES];
  257. [self initGCMRegistrationHandler];
  258. } else {
  259. NSLog(@"Using APNS Notification");
  260. [self setUsesGCM:NO];
  261. }
  262. id gcmSandBoxArg = [iosOptions objectForKey:@"gcmSandbox"];
  263. [self setGcmSandbox:@NO];
  264. if ([self usesGCM] &&
  265. (([gcmSandBoxArg isKindOfClass:[NSString class]] && [gcmSandBoxArg isEqualToString:@"true"]) ||
  266. [gcmSandBoxArg boolValue]))
  267. {
  268. NSLog(@"Using GCM Sandbox");
  269. [self setGcmSandbox:@YES];
  270. }
  271. if (notificationMessage) // if there is a pending startup notification
  272. [self notificationReceived]; // go ahead and process it
  273. }];
  274. }
  275. - (UIMutableUserNotificationAction *)createAction:(NSDictionary *)dictionary {
  276. UIMutableUserNotificationAction *myAction = [[UIMutableUserNotificationAction alloc] init];
  277. myAction = [[UIMutableUserNotificationAction alloc] init];
  278. myAction.identifier = [dictionary objectForKey:@"callback"];
  279. myAction.title = [dictionary objectForKey:@"title"];
  280. id mode =[dictionary objectForKey:@"foreground"];
  281. if (mode == nil || ([mode isKindOfClass:[NSString class]] && [mode isEqualToString:@"false"]) || ![mode boolValue]) {
  282. myAction.activationMode = UIUserNotificationActivationModeBackground;
  283. } else {
  284. myAction.activationMode = UIUserNotificationActivationModeForeground;
  285. }
  286. id destructive = [dictionary objectForKey:@"destructive"];
  287. if (destructive == nil || ([destructive isKindOfClass:[NSString class]] && [destructive isEqualToString:@"false"]) || ![destructive boolValue]) {
  288. myAction.destructive = NO;
  289. } else {
  290. myAction.destructive = YES;
  291. }
  292. myAction.authenticationRequired = NO;
  293. return myAction;
  294. }
  295. - (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  296. if (self.callbackId == nil) {
  297. NSLog(@"Unexpected call to didRegisterForRemoteNotificationsWithDeviceToken, ignoring: %@", deviceToken);
  298. return;
  299. }
  300. NSLog(@"Push Plugin register success: %@", deviceToken);
  301. NSMutableDictionary *results = [NSMutableDictionary dictionary];
  302. NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
  303. stringByReplacingOccurrencesOfString:@">" withString:@""]
  304. stringByReplacingOccurrencesOfString: @" " withString: @""];
  305. [results setValue:token forKey:@"deviceToken"];
  306. #if !TARGET_IPHONE_SIMULATOR
  307. // Get Bundle Info for Remote Registration (handy if you have more than one app)
  308. [results setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] forKey:@"appName"];
  309. [results setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"appVersion"];
  310. // Check what Notifications the user has turned on. We registered for all three, but they may have manually disabled some or all of them.
  311. #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
  312. NSUInteger rntypes;
  313. if (!SYSTEM_VERSION_LESS_THAN(@"8.0")) {
  314. rntypes = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
  315. } else {
  316. rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
  317. }
  318. // Set the defaults to disabled unless we find otherwise...
  319. NSString *pushBadge = @"disabled";
  320. NSString *pushAlert = @"disabled";
  321. NSString *pushSound = @"disabled";
  322. // Check what Registered Types are turned on. This is a bit tricky since if two are enabled, and one is off, it will return a number 2... not telling you which
  323. // one is actually disabled. So we are literally checking to see if rnTypes matches what is turned on, instead of by number. The "tricky" part is that the
  324. // single notification types will only match if they are the ONLY one enabled. Likewise, when we are checking for a pair of notifications, it will only be
  325. // true if those two notifications are on. This is why the code is written this way
  326. if(rntypes & UIRemoteNotificationTypeBadge){
  327. pushBadge = @"enabled";
  328. }
  329. if(rntypes & UIRemoteNotificationTypeAlert) {
  330. pushAlert = @"enabled";
  331. }
  332. if(rntypes & UIRemoteNotificationTypeSound) {
  333. pushSound = @"enabled";
  334. }
  335. [results setValue:pushBadge forKey:@"pushBadge"];
  336. [results setValue:pushAlert forKey:@"pushAlert"];
  337. [results setValue:pushSound forKey:@"pushSound"];
  338. // Get the users Device Model, Display Name, Token & Version Number
  339. UIDevice *dev = [UIDevice currentDevice];
  340. [results setValue:dev.name forKey:@"deviceName"];
  341. [results setValue:dev.model forKey:@"deviceModel"];
  342. [results setValue:dev.systemVersion forKey:@"deviceSystemVersion"];
  343. if([self usesGCM]) {
  344. GGLInstanceIDConfig *instanceIDConfig = [GGLInstanceIDConfig defaultConfig];
  345. instanceIDConfig.delegate = self;
  346. [[GGLInstanceID sharedInstance] startWithConfig:instanceIDConfig];
  347. [self setGcmRegistrationOptions: @{kGGLInstanceIDRegisterAPNSOption:deviceToken,
  348. kGGLInstanceIDAPNSServerTypeSandboxOption:[self gcmSandbox]}];
  349. [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:[self gcmSenderId]
  350. scope:kGGLInstanceIDScopeGCM
  351. options:[self gcmRegistrationOptions]
  352. handler:[self gcmRegistrationHandler]];
  353. GCMConfig *gcmConfig = [GCMConfig defaultConfig];
  354. gcmConfig.receiverDelegate = self;
  355. [[GCMService sharedInstance] startWithConfig:gcmConfig];
  356. } else {
  357. [self registerWithToken: token];
  358. }
  359. #endif
  360. }
  361. - (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  362. {
  363. if (self.callbackId == nil) {
  364. NSLog(@"Unexpected call to didFailToRegisterForRemoteNotificationsWithError, ignoring: %@", error);
  365. return;
  366. }
  367. NSLog(@"Push Plugin register failed");
  368. [self failWithMessage:@"" withError:error];
  369. }
  370. - (void)notificationReceived {
  371. NSLog(@"Notification received");
  372. if (notificationMessage && self.callbackId != nil)
  373. {
  374. NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:4];
  375. NSMutableDictionary* additionalData = [NSMutableDictionary dictionaryWithCapacity:4];
  376. for (id key in notificationMessage) {
  377. if ([key isEqualToString:@"aps"]) {
  378. id aps = [notificationMessage objectForKey:@"aps"];
  379. for(id key in aps) {
  380. NSLog(@"Push Plugin key: %@", key);
  381. id value = [aps objectForKey:key];
  382. if ([key isEqualToString:@"alert"]) {
  383. if ([value isKindOfClass:[NSDictionary class]]) {
  384. for (id messageKey in value) {
  385. id messageValue = [value objectForKey:messageKey];
  386. if ([messageKey isEqualToString:@"body"]) {
  387. [message setObject:messageValue forKey:@"message"];
  388. } else if ([messageKey isEqualToString:@"title"]) {
  389. [message setObject:messageValue forKey:@"title"];
  390. } else {
  391. [additionalData setObject:messageValue forKey:messageKey];
  392. }
  393. }
  394. }
  395. else {
  396. [message setObject:value forKey:@"message"];
  397. }
  398. } else if ([key isEqualToString:@"title"]) {
  399. [message setObject:value forKey:@"title"];
  400. } else if ([key isEqualToString:@"badge"]) {
  401. [message setObject:value forKey:@"count"];
  402. } else if ([key isEqualToString:@"sound"]) {
  403. [message setObject:value forKey:@"sound"];
  404. } else if ([key isEqualToString:@"image"]) {
  405. [message setObject:value forKey:@"image"];
  406. } else {
  407. [additionalData setObject:value forKey:key];
  408. }
  409. }
  410. } else {
  411. [additionalData setObject:[notificationMessage objectForKey:key] forKey:key];
  412. }
  413. }
  414. if (isInline) {
  415. [additionalData setObject:[NSNumber numberWithBool:YES] forKey:@"foreground"];
  416. } else {
  417. [additionalData setObject:[NSNumber numberWithBool:NO] forKey:@"foreground"];
  418. }
  419. if (coldstart) {
  420. [additionalData setObject:[NSNumber numberWithBool:YES] forKey:@"coldstart"];
  421. } else {
  422. [additionalData setObject:[NSNumber numberWithBool:NO] forKey:@"coldstart"];
  423. }
  424. [message setObject:additionalData forKey:@"additionalData"];
  425. // send notification message
  426. CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
  427. [pluginResult setKeepCallbackAsBool:YES];
  428. [self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
  429. self.notificationMessage = nil;
  430. }
  431. }
  432. - (void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command
  433. {
  434. NSMutableDictionary* options = [command.arguments objectAtIndex:0];
  435. int badge = [[options objectForKey:@"badge"] intValue] ?: 0;
  436. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
  437. NSString* message = [NSString stringWithFormat:@"app badge count set to %d", badge];
  438. CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
  439. [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
  440. }
  441. - (void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command
  442. {
  443. NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
  444. CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)badge];
  445. [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
  446. }
  447. - (void)hasPermission:(CDVInvokedUrlCommand *)command
  448. {
  449. BOOL enabled = NO;
  450. id<UIApplicationDelegate> appDelegate = [UIApplication sharedApplication].delegate;
  451. if ([appDelegate respondsToSelector:@selector(userHasRemoteNotificationsEnabled)]) {
  452. enabled = [appDelegate performSelector:@selector(userHasRemoteNotificationsEnabled)];
  453. }
  454. NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:1];
  455. [message setObject:[NSNumber numberWithBool:enabled] forKey:@"isEnabled"];
  456. CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
  457. [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
  458. }
  459. -(void)successWithMessage:(NSString *)message
  460. {
  461. if (self.callbackId != nil)
  462. {
  463. CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
  464. [self.commandDelegate sendPluginResult:commandResult callbackId:self.callbackId];
  465. }
  466. }
  467. -(void)registerWithToken:(NSString*)token; {
  468. // Send result to trigger 'registration' event but keep callback
  469. NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:1];
  470. [message setObject:token forKey:@"registrationId"];
  471. CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
  472. [pluginResult setKeepCallbackAsBool:YES];
  473. [self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
  474. }
  475. -(void)failWithMessage:(NSString *)message withError:(NSError *)error
  476. {
  477. NSString *errorMessage = (error) ? [NSString stringWithFormat:@"%@ - %@", message, [error localizedDescription]] : message;
  478. CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
  479. [self.commandDelegate sendPluginResult:commandResult callbackId:self.callbackId];
  480. }
  481. -(void) finish:(CDVInvokedUrlCommand*)command
  482. {
  483. NSLog(@"Push Plugin finish called");
  484. [self.commandDelegate runInBackground:^ {
  485. NSString* notId = [command.arguments objectAtIndex:0];
  486. UIApplication *app = [UIApplication sharedApplication];
  487. dispatch_async(dispatch_get_main_queue(), ^{
  488. [NSTimer scheduledTimerWithTimeInterval:0.1
  489. target:self
  490. selector:@selector(stopBackgroundTask:)
  491. userInfo:notId
  492. repeats:NO];
  493. });
  494. CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
  495. [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
  496. }];
  497. }
  498. -(void)stopBackgroundTask:(NSTimer*)timer
  499. {
  500. UIApplication *app = [UIApplication sharedApplication];
  501. NSLog(@"Push Plugin stopBackgroundTask called");
  502. if (handlerObj) {
  503. NSLog(@"Push Plugin handlerObj");
  504. completionHandler = [handlerObj[[timer userInfo]] copy];
  505. if (completionHandler) {
  506. NSLog(@"Push Plugin: stopBackgroundTask (remaining t: %f)", app.backgroundTimeRemaining);
  507. completionHandler(UIBackgroundFetchResultNewData);
  508. completionHandler = nil;
  509. }
  510. }
  511. }
  512. @end