forked from tidev/titanium-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TiApp.m
1584 lines (1309 loc) · 63.4 KB
/
TiApp.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2018 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <stdio.h>
#import "ImageLoader.h"
#import "Mimetypes.h"
#import "NSData+Additions.h"
#import "TiApp.h"
#import "TiBase.h"
#import "TiErrorController.h"
#import "TiExceptionHandler.h"
#import "TiSharedConfig.h"
#import "Webcolor.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreSpotlight/CoreSpotlight.h>
#import <QuartzCore/QuartzCore.h>
#import <libkern/OSAtomic.h>
#ifndef DISABLE_TI_LOG_SERVER
#import "TiLogServer.h"
#endif
TiApp *sharedApp;
int TiDebugPort = 2525;
NSString *TITANIUM_VERSION;
extern void UIColorFlushCache();
#define SHUTDOWN_TIMEOUT_IN_SEC 3
#define TIV @"TiVerify"
BOOL applicationInMemoryPanic = NO;
TI_INLINE void waitForMemoryPanicCleared(); //WARNING: This must never be run on main thread, or else there is a risk of deadlock!
@interface TiApp ()
- (void)checkBackgroundServices;
- (void)appBoot;
@end
@implementation TiApp
- (void)clearMemoryPanic
{
applicationInMemoryPanic = NO;
}
@synthesize window, controller;
@synthesize disableNetworkActivityIndicator;
@synthesize remoteNotification;
@synthesize pendingCompletionHandlers;
@synthesize backgroundTransferCompletionHandlers;
@synthesize localNotification;
@synthesize appBooted;
@synthesize userAgent;
+ (TiApp *)app
{
return sharedApp;
}
+ (TiRootViewController *)controller;
{
return [sharedApp controller];
}
- (JSContextGroupRef)contextGroup
{
if (contextGroup == nil) {
contextGroup = JSContextGroupCreate();
JSContextGroupRetain(contextGroup);
}
return contextGroup;
}
+ (JSContextGroupRef)contextGroup
{
return [sharedApp contextGroup];
}
- (NSMutableDictionary *)queuedBootEvents
{
if (queuedBootEvents == nil) {
queuedBootEvents = [[[NSMutableDictionary alloc] init] retain];
}
return queuedBootEvents;
}
- (NSMutableDictionary<NSString *, NSOrderedSet<id> *> *)queuedApplicationSelectors
{
if (_queuedApplicationSelectors == nil) {
_queuedApplicationSelectors = [[[NSMutableDictionary alloc] init] retain];
}
return _queuedApplicationSelectors;
}
- (void)startNetwork
{
ENSURE_UI_THREAD_0_ARGS;
if (OSAtomicIncrement32(&networkActivityCount) == 1) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:!disableNetworkActivityIndicator];
}
}
- (void)stopNetwork
{
ENSURE_UI_THREAD_0_ARGS;
if (OSAtomicDecrement32(&networkActivityCount) == 0) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
}
- (void)setDisableNetworkActivityIndicator:(BOOL)value
{
disableNetworkActivityIndicator = value;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:(!disableNetworkActivityIndicator && (networkActivityCount > 0))];
}
- (NSDictionary *)launchOptions
{
return launchOptions;
}
- (NSMutableSet<id> *)applicationDelegates
{
if (_applicationDelegates == nil) {
_applicationDelegates = [[NSMutableSet alloc] init];
}
return _applicationDelegates;
}
- (void)initController
{
sharedApp = self;
// attach our main view controller
controller = [[TiRootViewController alloc] init];
// attach our main view controller... IF we haven't already loaded the main window.
[window setRootViewController:controller];
[window makeKeyAndVisible];
}
- (BOOL)windowIsKeyWindow
{
return [window isKeyWindow];
}
- (UIView *)topMostView
{
UIWindow *currentKeyWindow_ = [[UIApplication sharedApplication] keyWindow];
return [[currentKeyWindow_ subviews] lastObject];
}
- (void)registerApplicationDelegate:(id)applicationDelegate
{
if ([[self applicationDelegates] containsObject:applicationDelegate]) {
NSLog(@"[WARN] Application delegate already exists in known application delegates!");
return;
}
[[self applicationDelegates] addObject:applicationDelegate];
}
- (void)unregisterApplicationDelegate:(id<UIApplicationDelegate>)applicationDelegate
{
if (![[self applicationDelegates] containsObject:applicationDelegate]) {
NSLog(@"[WARN] Application delegate does not exist in known application delegates!");
return;
}
[[self applicationDelegates] removeObject:applicationDelegate];
}
- (void)launchToUrl
{
Class ApplicationDefaults = NSClassFromString(@"ApplicationDefaults");
if (ApplicationDefaults == nil) {
return;
}
NSDictionary *launchDefaults = [ApplicationDefaults performSelector:@selector(launchUrl)];
if (launchDefaults != nil) {
UIApplication *app = [UIApplication sharedApplication];
NSURL *url = [NSURL URLWithString:[launchDefaults objectForKey:@"application-launch-url"]];
if ([app canOpenURL:url]) {
if ([TiUtils isIOSVersionOrGreater:@"10.0"]) {
[app openURL:url options:@{} completionHandler:nil];
} else {
[app openURL:url];
}
} else {
DebugLog(@"[WARN] The launch-url provided : %@ is invalid.", [launchDefaults objectForKey:@"application-launch-url"]);
}
}
}
- (void)createDefaultDirectories
{
NSError *error = nil;
[[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:&error];
if (error) {
DebugLog(@"[ERROR] %@ %@", error, [error userInfo]);
}
}
- (void)boot
{
DebugLog(@"[INFO] %@/%@ (%s.%@)",
[[TiSharedConfig defaultConfig] applicationName],
[[TiSharedConfig defaultConfig] applicationVersion],
TI_VERSION_STR,
[[TiSharedConfig defaultConfig] sdkVersion]);
sessionId = [[TiUtils createUUID] retain];
TITANIUM_VERSION = [[NSString stringWithCString:TI_VERSION_STR encoding:NSUTF8StringEncoding] retain];
[self appBoot];
}
- (void)appBoot
{
kjsBridge = [[KrollBridge alloc] initWithHost:self];
[kjsBridge boot:self url:nil preload:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (void)validator
{
[[[NSClassFromString(TIV) alloc] init] autorelease];
}
- (void)booted:(id)bridge
{
if ([bridge isKindOfClass:[KrollBridge class]]) {
DebugLog(@"[DEBUG] Application booted in %f ms", ([NSDate timeIntervalSinceReferenceDate] - started) * 1000);
fflush(stderr);
appBooted = YES;
if (launchedShortcutItem != nil) {
[self handleShortcutItem:launchedShortcutItem queueToBootIfNotLaunched:YES];
RELEASE_TO_NIL(launchedShortcutItem);
}
if (queuedBootEvents != nil) {
for (NSString *notificationName in queuedBootEvents) {
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:self userInfo:[queuedBootEvents objectForKey:notificationName]];
}
RELEASE_TO_NIL(queuedBootEvents);
}
if (_applicationDelegates != nil) {
for (NSString *selectorString in [self queuedApplicationSelectors]) {
[self tryToInvokeSelector:NSSelectorFromString(selectorString) withArguments:[[self queuedApplicationSelectors] objectForKey:selectorString]];
}
[_queuedApplicationSelectors removeAllObjects];
}
TiThreadPerformOnMainThread(^{
[self validator];
},
YES);
}
}
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[TiExceptionHandler defaultExceptionHandler];
#ifndef DISABLE_TI_LOG_SERVER
[[TiLogServer defaultLogServer] start];
#endif
[self initController];
[self launchToUrl];
[self boot];
}
- (UIView *)splashScreenView
{
if (splashScreenView == nil) {
if ([TiUtils isUsingLaunchScreenStoryboard]) {
UIStoryboard *launchScreen = [UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil];
UIViewController *launchScreenViewController = [launchScreen instantiateInitialViewController];
splashScreenView = [[launchScreenViewController view] retain];
} else {
splashScreenView = [[UIImageView alloc] init];
[splashScreenView setBackgroundColor:[UIColor yellowColor]];
[splashScreenView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
[splashScreenView setContentMode:UIViewContentModeScaleToFill];
UIDeviceOrientation imageOrientation;
UIUserInterfaceIdiom imageIdiom;
UIImage *defaultImage = [controller defaultImageForOrientation:
(UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation]
resultingOrientation:&imageOrientation
idiom:&imageIdiom];
[(UIImageView *)splashScreenView setImage:defaultImage];
[splashScreenView setFrame:[[UIScreen mainScreen] bounds]];
}
}
return splashScreenView;
}
- (void)generateNotification:(NSDictionary *)dict
{
// Check and see if any keys from APS and the rest of the dictionary match; if they do, just
// bump out the dictionary as-is
remoteNotification = [[NSMutableDictionary alloc] initWithDictionary:dict];
NSDictionary *aps = [dict objectForKey:@"aps"];
for (NSString *key in aps) {
if ([dict objectForKey:key] != nil) {
DebugLog(@"[WARN] Conflicting keys in push APS dictionary and notification dictionary `%@`, not copying to toplevel from APS", key);
continue;
}
[remoteNotification setValue:[aps valueForKey:key] forKey:key];
}
}
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(UIApplicationExtensionPointIdentifier)extensionPointIdentifier
{
BOOL allowsCustomKeyboard = [TiUtils boolValue:[[TiApp tiAppProperties] objectForKey:@"allow-custom-keyboards"] def:YES];
[self tryToInvokeSelector:@selector(application:shouldAllowExtensionPointIdentifier:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, extensionPointIdentifier, nil]];
if ([extensionPointIdentifier isEqualToString:UIApplicationKeyboardExtensionPointIdentifier] && !allowsCustomKeyboard) {
return NO;
}
return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions_
{
started = [NSDate timeIntervalSinceReferenceDate];
[TiExceptionHandler defaultExceptionHandler];
#ifndef DISABLE_TI_LOG_SERVER
[[TiLogServer defaultLogServer] start];
#endif
// Initialize the root-window
window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// Initialize the launch options to be used by the client
launchOptions = [[NSMutableDictionary alloc] initWithDictionary:launchOptions_];
// Initialize the root-controller
[self initController];
// If we have a APNS-UUID, assign it
NSString *apnsUUID = [[NSUserDefaults standardUserDefaults] stringForKey:@"APNSRemoteDeviceUUID"];
if (apnsUUID != nil) {
remoteDeviceUUID = [apnsUUID copy];
}
// iOS 10+: Register our notification delegate
if ([TiUtils isIOSVersionOrGreater:@"10.0"]) {
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
}
// Get some launch options to validate before finish launching. Some of them
// need to be mapepd from native to JS-types to be used by the client
NSURL *urlOptions = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
NSString *sourceBundleId = [launchOptions objectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
NSDictionary *_remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
UILocalNotification *_localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSNumber *launchedLocation = [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey];
UIApplicationShortcutItem *shortcut = [launchOptions objectForKey:UIApplicationLaunchOptionsShortcutItemKey];
// Map background location key
if (launchedLocation != nil) {
[launchOptions setObject:launchedLocation forKey:@"launchOptionsLocationKey"];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsLocationKey];
}
// Map local notification
if (_localNotification != nil) {
localNotification = [[[self class] dictionaryWithLocalNotification:_localNotification] retain];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
// Queue the "localnotificationaction" event for iOS 9 and lower.
// For iOS 10+, the "userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler" delegate handles it
if ([TiUtils isIOSVersionLower:@"9.0"]) {
[self tryToPostNotification:localNotification withNotificationName:kTiLocalNotificationAction completionHandler:nil];
}
}
// Map launched URL
if (urlOptions != nil) {
[launchOptions setObject:[urlOptions absoluteString] forKey:@"url"];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsURLKey];
}
// Map launched App-ID
if (sourceBundleId != nil) {
[launchOptions setObject:sourceBundleId forKey:@"source"];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
}
// Generate remote notification of available
if (_remoteNotification != nil) {
[self generateNotification:_remoteNotification];
}
if (shortcut != nil) {
launchedShortcutItem = [shortcut retain];
}
// Queue selector for usage in modules / Hyperloop
[self tryToInvokeSelector:@selector(application:didFinishLaunchingWithOptions:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, launchOptions_, nil]];
// If a "application-launch-url" is set, launch it directly
[self launchToUrl];
// Boot our kroll-core
[self boot];
// Create application support directory if not exists
[self createDefaultDirectories];
return YES;
}
// Handle URL-schemes / iOS >= 9
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)options
{
[self tryToInvokeSelector:@selector(application:openURL:options:)
withArguments:[NSOrderedSet orderedSetWithObjects:app, url, options, nil]];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsURLKey];
[launchOptions setObject:[url absoluteString] forKey:@"url"];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
[launchOptions setObject:[options objectForKey:UIApplicationOpenURLOptionsSourceApplicationKey] ?: [NSNull null] forKey:@"source"];
if (appBooted) {
[[NSNotificationCenter defaultCenter] postNotificationName:kTiApplicationLaunchedFromURL object:self userInfo:launchOptions];
} else {
[[self queuedBootEvents] setObject:launchOptions forKey:kTiApplicationLaunchedFromURL];
}
return YES;
}
// Handle URL-schemes / iOS < 9
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
[self tryToInvokeSelector:@selector(application:sourceApplication:annotation:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, sourceApplication, annotation, nil]];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsURLKey];
[launchOptions setObject:[url absoluteString] forKey:@"url"];
[launchOptions removeObjectForKey:UIApplicationLaunchOptionsSourceApplicationKey];
[launchOptions setObject:sourceApplication ?: [NSNull null] forKey:@"source"];
if (appBooted) {
[[NSNotificationCenter defaultCenter] postNotificationName:kTiApplicationLaunchedFromURL object:self userInfo:launchOptions];
} else {
[[self queuedBootEvents] setObject:launchOptions forKey:kTiApplicationLaunchedFromURL];
}
return YES;
}
#pragma mark Background Fetch
#ifdef USE_TI_FETCH
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[self tryToInvokeSelector:@selector(application:performFetchWithCompletionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, [completionHandler copy], nil]];
//Only for simulator builds
NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
if ([backgroundModes containsObject:@"fetch"]) {
// Generate unique key with timestamp.
NSString *key = [NSString stringWithFormat:@"Fetch-%f", [[NSDate date] timeIntervalSince1970]];
// Store the completionhandler till we can come back and send appropriate message.
if (pendingCompletionHandlers == nil) {
pendingCompletionHandlers = [[NSMutableDictionary alloc] init];
}
[pendingCompletionHandlers setObject:[[completionHandler copy] autorelease] forKey:key];
[self tryToPostBackgroundModeNotification:[NSMutableDictionary dictionaryWithObjectsAndKeys:key, @"handlerId", nil]
withNotificationName:kTiBackgroundFetchNotification];
// We will go ahead and keeper a timer just in case the user returns the value too late - this is the worst case scenario.
NSTimer *flushTimer = [NSTimer timerWithTimeInterval:TI_BACKGROUNDFETCH_MAX_INTERVAL target:self selector:@selector(fireCompletionHandler:) userInfo:key repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:flushTimer forMode:NSDefaultRunLoopMode];
}
}
#endif
#pragma mark Remote and Local Notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[self tryToInvokeSelector:@selector(application:didRegisterUserNotificationSettings:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, notificationSettings, nil]];
[[NSNotificationCenter defaultCenter] postNotificationName:kTiUserNotificationSettingsNotification
object:self
userInfo:@{ @"userNotificationSettings" : notificationSettings }];
}
// iOS 12+
- (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification
{
// Unused so far, may expose as an event in the future?
}
// iOS 10+
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
// For backwards compatibility with iOS < 10, we do not show notifications while the app is in foreground, but make it configurable
// @fixme this is not documented and was silently introduced in TIMOB-26399
BOOL showInForeground = [TiUtils boolValue:notification.request.content.userInfo[@"showInForeground"] def:NO];
BOOL isRemote = [notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class];
if (isRemote) {
if ([self respondsToSelector:@selector(application:didReceiveRemoteNotification:)]) {
[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:notification.request.content.userInfo];
}
} else {
RELEASE_TO_NIL(localNotification);
localNotification = [[TiApp dictionaryWithUserNotification:notification
withIdentifier:notification.request.identifier] retain];
[self tryToPostNotification:localNotification withNotificationName:kTiLocalNotification completionHandler:nil];
}
if (showInForeground) {
completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
} else {
completionHandler(UNNotificationPresentationOptionNone);
}
}
// iOS 10+
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
BOOL isRemote = [response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class];
if (isRemote) {
NSMutableDictionary *responseInfo = nil;
if ([response isKindOfClass:[UNTextInputNotificationResponse class]]) {
responseInfo = [NSMutableDictionary dictionary];
[responseInfo setValue:((UNTextInputNotificationResponse *)response).userText forKey:UIUserNotificationActionResponseTypedTextKey];
}
if ([UNNotificationDefaultActionIdentifier isEqualToString:response.actionIdentifier]) {
if ([self respondsToSelector:@selector(application:didReceiveRemoteNotification:)]) {
[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:response.notification.request.content.userInfo];
}
completionHandler();
} else {
[self application:[UIApplication sharedApplication] handleActionWithIdentifier:response.actionIdentifier forRemoteNotification:response.notification.request.content.userInfo withResponseInfo:responseInfo completionHandler:completionHandler];
}
} else {
//NOTE Local notifications should be handled similar to BG above which ultimately calls handleRemoteNotificationWithIdentifier as this will allow BG Actions to execute.
RELEASE_TO_NIL(localNotification);
localNotification = [[[self class] dictionaryWithUserNotification:response.notification
withIdentifier:response.actionIdentifier] retain];
if ([response isKindOfClass:[UNTextInputNotificationResponse class]]) {
[localNotification setValue:((UNTextInputNotificationResponse *)response).userText forKey:@"typedText"];
}
[self tryToPostNotification:localNotification withNotificationName:kTiLocalNotificationAction completionHandler:completionHandler];
}
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
RELEASE_TO_NIL(localNotification);
localNotification = [[TiApp dictionaryWithLocalNotification:notification withIdentifier:identifier] retain];
[localNotification setValue:responseInfo[UIUserNotificationActionResponseTypedTextKey] forKey:@"typedText"];
[self tryToInvokeSelector:@selector(application:handleActionWithIdentifier:forLocalNotification:withResponseInfo:completionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, identifier, notification, responseInfo, completionHandler, nil]];
[self tryToPostNotification:localNotification withNotificationName:kTiLocalNotificationAction completionHandler:completionHandler];
}
// iOS 9+
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
[self tryToInvokeSelector:@selector(application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, identifier, userInfo, responseInfo, completionHandler, nil]];
[self handleRemoteNotificationWithIdentifier:identifier
andUserInfo:userInfo
responseInfo:responseInfo
completionHandler:completionHandler];
}
// iOS < 9
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
[self tryToInvokeSelector:@selector(application:handleActionWithIdentifier:forRemoteNotification:completionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, identifier, userInfo, [completionHandler copy], nil]];
[self handleRemoteNotificationWithIdentifier:identifier
andUserInfo:userInfo
responseInfo:nil // iOS 9+ only
completionHandler:completionHandler];
}
#pragma mark Apple Watchkit handleWatchKitExtensionRequest
- (void)application:(UIApplication *)application
handleWatchKitExtensionRequest:(NSDictionary *)userInfo
reply:(void (^)(NSDictionary *replyInfo))reply
{
// Generate unique key with timestamp.
NSString *key = [NSString stringWithFormat:@"watchkit-reply-%f", [[NSDate date] timeIntervalSince1970]];
if (pendingReplyHandlers == nil) {
pendingReplyHandlers = [[NSMutableDictionary alloc] init];
}
[pendingReplyHandlers setObject:[[reply copy] autorelease] forKey:key];
NSMutableDictionary *dic = [[[NSMutableDictionary alloc] init] autorelease];
[dic setObject:key forKey:@"handlerId"];
if (userInfo != nil) {
[dic setObject:userInfo forKey:@"userInfo"];
}
[self tryToInvokeSelector:@selector(application:handleWatchKitExtensionRequest:reply:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, userInfo, [reply copy], nil]];
[[NSNotificationCenter defaultCenter] postNotificationName:kTiWatchKitExtensionRequest object:self userInfo:dic];
}
- (void)watchKitExtensionRequestHandler:(id)key withUserInfo:(NSDictionary *)userInfo
{
if (pendingReplyHandlers == nil) {
DebugLog(@"[ERROR] No WatchKitExtensionRequest have been recieved yet");
return;
}
if ([pendingReplyHandlers objectForKey:key]) {
void (^replyBlock)(NSDictionary *input);
replyBlock = [pendingReplyHandlers objectForKey:key];
replyBlock(userInfo);
[pendingReplyHandlers removeObjectForKey:key];
} else {
DebugLog(@"[ERROR] The specified WatchKitExtensionRequest Handler with ID: %@ has already expired or removed from the system", key);
}
}
#pragma mark -
#pragma mark Helper Methods
- (void)invokeSelector:(SEL)selector withArguments:(NSOrderedSet<id> *)arguments onDelegate:(id)delegate
{
NSInteger index = 2; // Index 0 and 1 are reserved for the invocation internals ("self" and "_cmd")
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[delegate methodSignatureForSelector:selector]];
[inv setSelector:selector];
[inv setTarget:delegate];
for (id obj in arguments) {
// clang-format off
[inv setArgument:&(obj) atIndex:index++];
// clang-format on
}
[inv invoke];
}
- (void)tryToInvokeSelector:(SEL)selector withArguments:(NSOrderedSet<id> *)arguments
{
NSString *selectorString = NSStringFromSelector(selector);
if (appBooted && _applicationDelegates != nil) {
for (id applicationDelegate in _applicationDelegates) {
if ([applicationDelegate respondsToSelector:selector]) {
[self invokeSelector:selector withArguments:arguments onDelegate:applicationDelegate];
}
}
} else if (!appBooted && _applicationDelegates == nil) {
[[self queuedApplicationSelectors] setObject:arguments forKey:selectorString];
}
}
- (void)tryToPostNotification:(NSDictionary *)_notification withNotificationName:(NSString *)_notificationName completionHandler:(void (^)())completionHandler
{
typedef void (^NotificationBlock)();
NotificationBlock myNotificationBlock = ^void() {
[[NSNotificationCenter defaultCenter] postNotificationName:_notificationName object:self userInfo:_notification];
if (completionHandler != nil) {
completionHandler();
}
};
if (appBooted) {
myNotificationBlock();
} else {
[[self queuedBootEvents] setObject:_notification forKey:_notificationName];
}
}
- (void)tryToPostBackgroundModeNotification:(NSMutableDictionary *)userInfo withNotificationName:(NSString *)notificationName
{
// Check to see if the app booted and we still have the completion handler in the system
NSString *key = [userInfo objectForKey:@"handlerId"];
BOOL shouldContinue = NO;
if ([key rangeOfString:@"Session"].location != NSNotFound) {
if ([backgroundTransferCompletionHandlers objectForKey:key] != nil) {
shouldContinue = YES;
}
} else if ([pendingCompletionHandlers objectForKey:key] != nil) {
shouldContinue = YES;
}
if (!shouldContinue) {
return;
}
if (appBooted) {
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:self userInfo:userInfo];
} else {
[[self queuedBootEvents] setObject:userInfo forKey:notificationName];
}
}
// Clear out the pending completion handlers
- (void)flushCompletionHandlerQueue
{
if (pendingCompletionHandlers != nil) {
for (NSString *key in [pendingCompletionHandlers allKeys]) {
// Do not remove from the pending handlers for now, as it's removed after the enumeration finished
[self performCompletionHandlerWithKey:key andResult:UIBackgroundFetchResultFailed removeAfterExecution:NO];
}
}
RELEASE_TO_NIL(pendingCompletionHandlers);
}
// This method gets called when the wall clock runs out and the completion handler is still there
- (void)fireCompletionHandler:(NSTimer *)timer
{
NSString *key = (NSString *)timer.userInfo;
if ([pendingCompletionHandlers objectForKey:key]) {
// Send an event notifying the developer that the background-fetch failed
[self performCompletionHandlerWithKey:key andResult:UIBackgroundFetchResultFailed removeAfterExecution:YES];
}
}
// Gets called when user ends finishes with backgrounding stuff. By default this would always be called with UIBackgroundFetchResultNoData.
- (void)performCompletionHandlerWithKey:(NSString *)key andResult:(UIBackgroundFetchResult)result removeAfterExecution:(BOOL)removeAfterExecution
{
if ([pendingCompletionHandlers objectForKey:key]) {
void (^completionHandler)(UIBackgroundFetchResult) = [pendingCompletionHandlers objectForKey:key];
completionHandler(result);
if (removeAfterExecution) {
[pendingCompletionHandlers removeObjectForKey:key];
}
} else {
DebugLog(@"[ERROR] The specified completion handler with ID = %@ has already expired or been removed from the system", key);
}
}
//Called to mark the end of background transfer while in the background.
- (void)performCompletionHandlerForBackgroundTransferWithKey:(NSString *)key
{
if ([backgroundTransferCompletionHandlers objectForKey:key] != nil) {
void (^completionHandler)();
completionHandler = [backgroundTransferCompletionHandlers objectForKey:key];
[backgroundTransferCompletionHandlers removeObjectForKey:key];
completionHandler();
} else {
DebugLog(@"[ERROR] The specified completion handler with ID = %@ has already expired or been removed from the system", key);
}
}
#pragma mark
#pragma mark Remote Notifications
#ifdef USE_TI_SILENTPUSH
// Delegate callback for Silent Remote Notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
[self tryToInvokeSelector:@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, userInfo, [completionHandler copy], nil]];
NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
if ([backgroundModes containsObject:@"remote-notification"]) {
// Generate unique key with timestamp.
NSString *key = [NSString stringWithFormat:@"SilentPush-%f", [[NSDate date] timeIntervalSince1970]];
// Store the completionhandler till we can come back and send appropriate message.
if (pendingCompletionHandlers == nil) {
pendingCompletionHandlers = [[NSMutableDictionary alloc] init];
}
[pendingCompletionHandlers setObject:[[completionHandler copy] autorelease] forKey:key];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:key, @"handlerId", nil];
[dict addEntriesFromDictionary:userInfo];
[self tryToPostBackgroundModeNotification:dict
withNotificationName:kTiSilentPushNotification];
// We will go ahead and keeper a timer just in case the user returns the value too late - this is the worst case scenario.
NSTimer *flushTimer = [NSTimer timerWithTimeInterval:TI_BACKGROUNDFETCH_MAX_INTERVAL target:self selector:@selector(fireCompletionHandler:) userInfo:key repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:flushTimer forMode:NSDefaultRunLoopMode];
}
}
#endif
#pragma mark Background Transfer Service
//Delegate callback for Background Transfer completes.
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
{
// Generate unique key with timestamp.
NSString *key = [NSString stringWithFormat:@"Session-%f", [[NSDate date] timeIntervalSince1970]];
// Store the completionhandler till we can come back and send appropriate message.
if (backgroundTransferCompletionHandlers == nil) {
backgroundTransferCompletionHandlers = [[NSMutableDictionary alloc] init];
}
[backgroundTransferCompletionHandlers setObject:[[completionHandler copy] autorelease] forKey:key];
[self tryToInvokeSelector:@selector(application:handleEventsForBackgroundURLSession:completionHandler:)
withArguments:[NSOrderedSet orderedSetWithObjects:application, identifier, [completionHandler copy], nil]];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:identifier, @"sessionId",
key, @"handlerId", nil];
[self tryToPostBackgroundModeNotification:dict withNotificationName:kTiBackgroundTransfer];
}
#pragma mark Background Transfer Service Delegates.
//TODO: Move these delegates to the module post 3.2.0
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// Copy downloaded file from location to tempFile (in NSTemporaryDirectory), because file in location will be removed after delegate completes
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destinationFilename = location.lastPathComponent;
NSURL *destinationURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:destinationFilename];
if ([fileManager fileExistsAtPath:[destinationURL path]]) {
[fileManager removeItemAtURL:destinationURL error:nil];
}
BOOL success = [fileManager copyItemAtURL:location toURL:destinationURL error:&error];
TiBlob *downloadedData;
if (!success) {
DebugLog(@"Unable to copy temp file. Error: %@", [error localizedDescription]);
downloadedData = [[[TiBlob alloc] initWithData:[NSData dataWithContentsOfURL:location] mimetype:[Mimetypes mimeTypeForExtension:[location absoluteString]]] autorelease];
} else {
downloadedData = [[[TiBlob alloc] initWithFile:[destinationURL path]] autorelease];
}
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger:downloadTask.taskIdentifier], @"taskIdentifier",
downloadedData, @"data", nil];
if (session.configuration.identifier) {
[dict setObject:session.configuration.identifier forKey:@"sessionIdentifier"];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kTiURLDownloadFinished object:self userInfo:dict];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger:downloadTask.taskIdentifier], @"taskIdentifier",
[NSNumber numberWithUnsignedLongLong:bytesWritten], @"bytesWritten",
[NSNumber numberWithUnsignedLongLong:totalBytesWritten], @"totalBytesWritten",
[NSNumber numberWithUnsignedLongLong:totalBytesExpectedToWrite], @"totalBytesExpectedToWrite", nil];
if (session.configuration.identifier) {
[dict setObject:session.configuration.identifier forKey:@"sessionIdentifier"];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kTiURLDowloadProgress object:self userInfo:dict];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:NUMUINTEGER(task.taskIdentifier), @"taskIdentifier",
[NSNumber numberWithUnsignedLongLong:bytesSent], @"bytesSent",
[NSNumber numberWithUnsignedLongLong:totalBytesSent], @"totalBytesSent",
[NSNumber numberWithUnsignedLongLong:totalBytesExpectedToSend], @"totalBytesExpectedToSend", nil];
if (session.configuration.identifier) {
[dict setObject:session.configuration.identifier forKey:@"sessionIdentifier"];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kTiURLUploadProgress object:self userInfo:dict];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
if (!uploadTaskResponses) {
uploadTaskResponses = [[NSMutableDictionary alloc] init];
}
//This dictionary will mutate if delegate is called
NSMutableDictionary *responseObj = [uploadTaskResponses objectForKey:@(dataTask.taskIdentifier)];
if (!responseObj) {
NSMutableData *responseData = [NSMutableData dataWithData:data];
NSInteger statusCode = [(NSHTTPURLResponse *)[dataTask response] statusCode];
responseObj = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(statusCode), @"statusCode", responseData, @"responseData", nil];
[uploadTaskResponses setValue:responseObj forKey:(NSString *)@(dataTask.taskIdentifier)];
} else {
[[responseObj objectForKey:@"responseData"] appendData:data];
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger:task.taskIdentifier], @"taskIdentifier",
nil];
if (session.configuration.identifier) {
[dict setObject:session.configuration.identifier forKey:@"sessionIdentifier"];
}
if (error) {
NSDictionary *errorinfo = [NSDictionary dictionaryWithObjectsAndKeys:@(NO), @"success",
@([error code]), @"errorCode",
[error localizedDescription], @"message",
nil];
[dict addEntriesFromDictionary:errorinfo];
} else {
NSMutableDictionary *responseObj = [uploadTaskResponses objectForKey:@(task.taskIdentifier)];
if (responseObj != nil) {
// We only send "responseText" as the "responsesData" is only set with data from uploads
NSString *responseText = [[NSString alloc] initWithData:[responseObj objectForKey:@"responseData"] encoding:NSUTF8StringEncoding];
NSInteger statusCode = [[responseObj valueForKey:@"statusCode"] integerValue];
[uploadTaskResponses removeObjectForKey:@(task.taskIdentifier)];
NSDictionary *successResponse = [NSMutableDictionary dictionaryWithObjectsAndKeys:@(YES), @"success",
@(0), @"errorCode",
responseText, @"responseText",
@(statusCode), @"statusCode",
nil];
[dict addEntriesFromDictionary:successResponse];
RELEASE_TO_NIL(responseText);
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:kTiURLSessionCompleted object:self userInfo:dict];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
NSDictionary *dict = nil;
if (session.configuration.identifier) {
dict = @{ @"sessionIdentifier" : session.configuration.identifier };
}
[[NSNotificationCenter defaultCenter] postNotificationName:kTiURLSessionEventsCompleted object:self userInfo:dict];
}
#pragma mark
- (void)applicationWillTerminate:(UIApplication *)application
{
[self tryToInvokeSelector:@selector(applicationWillTerminate:)
withArguments:[NSOrderedSet orderedSetWithObject:application]];
NSNotificationCenter *theNotificationCenter = [NSNotificationCenter defaultCenter];
_willTerminate = YES;
//This will send out the 'close' message.
[theNotificationCenter postNotificationName:kTiWillShutdownNotification object:self];
NSCondition *condition = [[NSCondition alloc] init];