This repository was archived by the owner on Dec 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathMyMainViewController.m
More file actions
executable file
·670 lines (562 loc) · 26.4 KB
/
MyMainViewController.m
File metadata and controls
executable file
·670 lines (562 loc) · 26.4 KB
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
#import <objc/runtime.h>
#import "MyMainViewController.h"
#import <Cordova/CDVTimer.h>
#import <Cordova/CDVLocalStorage.h>
#import <Cordova/CDVUserAgentUtil.h>
#import <Cordova/CDVWebViewDelegate.h>
#import <Cordova/CDVViewController.h>
#import <Cordova/CDVURLProtocol.h>
#import "CDVWebViewUIDelegate.h"
#import "ReroutingUIWebView.h"
#import "AppDelegate+WKWebViewPolyfill.h"
@interface CDVViewController ()
@property (nonatomic, readwrite, retain) NSArray *startupPluginNames;
@end
@interface MyMainViewController () {
NSInteger _userAgentLockToken;
CDVWebViewDelegate* _webViewDelegate;
CDVWebViewUIDelegate* _webViewUIDelegate;
BOOL _targetExistsLocally;
NSTimer* _crashRecoveryTimer;
BOOL _crashRecoveryActive;
NSURL *_startURL;
}
@end
@implementation MyMainViewController
@synthesize alreadyLoaded;
- (id)init
{
self = [super init];
if (self) {
// Save the path for our /www/ files
NSURL* startURL = [NSURL URLWithString:self.startPage];
NSString* startFilePath = [self.commandDelegate pathForResource:[startURL path]];
_targetExistsLocally = [[NSFileManager defaultManager]
fileExistsAtPath:startFilePath];
startFilePath = [startFilePath stringByDeletingLastPathComponent];
self.wwwFolderName = startFilePath;
self.alreadyLoaded = false;
}
if (![self settingForKey:@"DisableLocalStorageSyncWithUIWebView"] || ![[self settingForKey:@"DisableLocalStorageSyncWithUIWebView"] boolValue]) {
// configure listeners which fires when the application goes away
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyLocalStorageToUIWebView:)
name:UIApplicationWillTerminateNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyLocalStorageToUIWebView:)
name:UIApplicationWillResignActiveNotification object:nil];
}
// and some more for custom url schemes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationLaunchedWithUrl:) name:CDVPluginHandleOpenURLNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationPageDidLoad:) name:CDVPageDidLoadNotification object:nil];
return self;
}
- (void)applicationLaunchedWithUrl:(NSNotification*)notification {
NSURL *url = [notification object];
self.url = url;
// warm-start handler
if (self.pageLoaded) {
[self processOpenUrl:self.url pageLoaded:YES];
self.url = nil;
}
}
- (void)applicationPageDidLoad:(NSNotification*)notification {
// cold-start handler
self.pageLoaded = YES;
if (self.url) {
[self processOpenUrl:self.url pageLoaded:YES];
self.url = nil;
}
}
- (void)processOpenUrl:(NSURL*)url pageLoaded:(BOOL)pageLoaded {
if (!pageLoaded) {
// query the webview for readystate
NSString* readyState = [self.webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];
pageLoaded = [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"];
}
if (pageLoaded) {
// calls into javascript global function 'handleOpenURL'
NSString* jsString = [NSString stringWithFormat:@"document.addEventListener('deviceready',function(){if (typeof handleOpenURL === 'function') { handleOpenURL(\"%@\");}});", url];
[self.wkWebView evaluateJavaScript:jsString completionHandler:nil];
} else {
// save for when page has loaded
self.url = url;
}
}
- (void)copyLocalStorageToUIWebView:(NSNotification*)notification {
if (self.uiWebViewLS != nil && self.wkWebViewLS != nil) {
[[CDVLocalStorage class] copyFrom:self.wkWebViewLS to:self.uiWebViewLS error:nil];
}
}
#pragma mark View Rotation Event Handling
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
self.wkWebView.frame = self.view.bounds;
[self.wkWebView layoutIfNeeded];
} completion:nil];
}
#pragma mark View lifecycle
- (void)createGapView:(WKWebViewConfiguration*) config
{
CGRect webViewBounds = self.view.bounds;
webViewBounds.origin = self.view.bounds.origin;
self.wkWebView = [self newCordovaWKWebViewWithFrame:webViewBounds wkWebViewConfig:config];
self.wkWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
/*
#ifdef __IPHONE_9_0
// 3D touch-triggered URL preview feature -
// setting this to the default value, just to remind myself to play with it once I have a 6s.
self.wkWebView.allowsLinkPreview = NO;
#endif
*/
[self.wkWebView setOpaque:NO];
NSString* setting = @"BackgroundColor";
if ([self settingForKey:setting]) {
self.wkWebView.backgroundColor = [self colorFromHexString:[self settingForKey:setting]];
self.view.backgroundColor = self.wkWebView.backgroundColor;
} else {
self.wkWebView.backgroundColor = [UIColor clearColor];
self.view.backgroundColor = [UIColor whiteColor];
}
_webViewOperationsDelegate = [[CDVWebViewOperationsDelegate alloc] initWithWebView:self.webView];
[self.view addSubview:self.wkWebView];
[self.view sendSubviewToBack:self.wkWebView];
// plugins may do self.webView.superview which would evaluate to nil if we don't do this
self.webView.hidden = true;
[self.view addSubview:self.webView];
[self.view sendSubviewToBack:self.webView];
}
- (void)recoverFromCrash
{
// When an empty title is returned, WkWebView has crashed
NSString* title = self.wkWebView.title;
if ((title == nil) || [title isEqualToString:@""]) {
if (_crashRecoveryActive) {
NSLog(@"WkWebView crash detected, recovering... ");
_crashRecoveryActive = false;
[_crashRecoveryTimer invalidate];
_crashRecoveryTimer = nil;
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate createWindowAndStartWebServer:true];
}
} else {
// Once the title has been reported back as valid, activate crash recovery
_crashRecoveryActive = true;
}
}
- (id)settingForKey:(NSString*)key
{
return [[self settings] objectForKey:[key lowercaseString]];
}
- (void)setSetting:(id)setting forKey:(NSString*)key
{
[[self settings] setObject:setting forKey:[key lowercaseString]];
}
// THIS FUNCTION WILL BE REMOVED WHEN WKWEBVIEW SUPPORTS FILE LOADING FROM OUTSIDE OF /tmp
- (NSURL *) copyToTMP:(NSURL *)url {
NSString *fullPath = url.path;
NSString *src = url.lastPathComponent;
// Does file already exist at tmp?
NSError *copyError = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:src]]) {
if (![[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent:src] error:©Error]) {
NSLog(@"Error deleting file: %@", [copyError localizedDescription]);
}
}
// Copy to tmp
if (![[NSFileManager defaultManager] copyItemAtPath:fullPath toPath:[NSTemporaryDirectory() stringByAppendingPathComponent:src] error:©Error]) {
NSLog(@"Error copying file: %@", [copyError localizedDescription]);
return url;
}
// Load from tmp
return [[NSURL alloc] initFileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:src]];
}
- (BOOL)copyFrom:(NSString*)src to:(NSString*)dest error:(NSError* __autoreleasing*)error
{
NSFileManager* fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:src]) {
NSString* errorString = [NSString stringWithFormat:@"%@ file does not exist.", src];
if (error != NULL) {
(*error) = [NSError errorWithDomain:@"TestDomainTODO"
code:1
userInfo:[NSDictionary dictionaryWithObject:errorString
forKey:NSLocalizedDescriptionKey]];
}
return NO;
}
BOOL destExists = [fileManager fileExistsAtPath:dest];
// remove the dest
if (destExists && ![fileManager removeItemAtPath:dest error:error]) {
return NO;
}
// create path to dest
if (!destExists && ![fileManager createDirectoryAtPath:[dest stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:error]) {
return NO;
}
// copy src to dest
return [fileManager copyItemAtPath:src toPath:dest error:error];
}
- (void)loadURL:(NSURL*)URL
{
self.alreadyLoaded = true;
// /////////////////
[CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
_userAgentLockToken = lockToken;
[CDVUserAgentUtil setUserAgent:self.userAgent lockToken:lockToken];
NSURLRequest* appReq = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
[self.wkWebView loadRequest:appReq];
}];
}
- (NSURL*)fixURL:(NSString*)URL
{
if ([URL hasPrefix:@"http"]) {
return [NSURL URLWithString:URL];
} else if ([URL hasPrefix:@"file"]) {
NSString* fixedStartPage = [URL stringByReplacingOccurrencesOfString:@"file://" withString:@""];
fixedStartPage = [fixedStartPage stringByReplacingOccurrencesOfString:NSHomeDirectory() withString:@""];
return [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%hu%@", self.port, fixedStartPage]];
} else {
return [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%hu/%@", self.port, URL]];
}
}
- (void)setServerPort:(unsigned short)port
{
if (self.alreadyLoaded) {
// If we already loaded for some reason, we don't care about the local port.
return;
} else {
self.port = port;
_startURL = [self fixURL:self.startPage];
[self loadURL:_startURL];
}
}
- (void)viewDidLoad
{
NSURL* appURL = nil;
NSString* loadErr = nil;
if ([self.startPage rangeOfString:@"://"].location != NSNotFound) {
appURL = [NSURL URLWithString:self.startPage];
} else if ([self.wwwFolderName rangeOfString:@"://"].location != NSNotFound) {
appURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", self.wwwFolderName, self.startPage]];
}
// iOS9 (runtime) compatibility
if (IsAtLeastiOSVersion(@"9.0")) {
appURL = _startURL;
}
//// Fix the iOS 5.1 SECURITY_ERR bug (CB-347), this must be before the webView is instantiated ////
NSString* backupWebStorageType = @"cloud"; // default value
id backupWebStorage = [self settingForKey:@"BackupWebStorage"];
if ([backupWebStorage isKindOfClass:[NSString class]]) {
backupWebStorageType = backupWebStorage;
}
[self setSetting:backupWebStorageType forKey:@"BackupWebStorage"];
if (IsAtLeastiOSVersion(@"5.1")) {
[CDVLocalStorage __fixupDatabaseLocationsWithBackupType:backupWebStorageType];
}
NSNumber* allowInlineMediaPlayback = [self settingForKey:@"AllowInlineMediaPlayback"];
BOOL mediaPlaybackRequiresUserAction = YES; // default value
if ([self settingForKey:@"MediaPlaybackRequiresUserAction"]) {
mediaPlaybackRequiresUserAction = [(NSNumber*)[self settingForKey:@"MediaPlaybackRequiresUserAction"] boolValue];
}
// // Instantiate the WebView ///////////////
if (!self.wkWebView) {
WKUserContentController* userContentController = [[WKUserContentController alloc] init];
if ([self conformsToProtocol:@protocol(WKScriptMessageHandler)]) {
[userContentController addScriptMessageHandler:self name:@"cordova"];
}
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
if ([allowInlineMediaPlayback boolValue]) {
config.allowsInlineMediaPlayback = YES;
}
config.mediaPlaybackRequiresUserAction = mediaPlaybackRequiresUserAction;
config.userContentController = userContentController;
BOOL suppressesIncrementalRendering = NO; // SuppressesIncrementalRendering - defaults to NO
if ([self settingForKey:@"SuppressesIncrementalRendering"] != nil) {
if ([self settingForKey:@"SuppressesIncrementalRendering"]) {
suppressesIncrementalRendering = [(NSNumber*)[self settingForKey:@"SuppressesIncrementalRendering"] boolValue];
}
}
config.suppressesIncrementalRendering = suppressesIncrementalRendering;
[self createGapView:config];
}
// Configure WebView
self.wkWebView.navigationDelegate = self;
// register this viewcontroller with the NSURLProtocol, only after the User-Agent is set
[CDVURLProtocol registerViewController:self];
// /////////////////
NSString* enableViewportScale = [self settingForKey:@"EnableViewportScale"];
// NOTE: setting these because this is largely a copy-paste of the super class, it's not actually used of course because this is the 'old' webView
self.webView.scalesPageToFit = [enableViewportScale boolValue];
// Fire up CDVLocalStorage to work-around WebKit storage limitations: on all iOS 5.1+ versions for local-only backups, but only needed on iOS 5.1 for cloud backup.
if (IsAtLeastiOSVersion(@"5.1") && (([backupWebStorageType isEqualToString:@"local"]) ||
([backupWebStorageType isEqualToString:@"cloud"] && !IsAtLeastiOSVersion(@"6.0")))) {
[self registerPlugin:[[CDVLocalStorage alloc] initWithWebView:self.webView] withClassName:NSStringFromClass([CDVLocalStorage class])];
};
/*
* This is for iOS 4.x, where you can allow inline <video> and <audio>, and also autoplay them
*/
if ([allowInlineMediaPlayback boolValue] && [self.webView respondsToSelector:@selector(allowsInlineMediaPlayback)]) {
self.webView.allowsInlineMediaPlayback = YES;
}
if ((mediaPlaybackRequiresUserAction == NO) && [self.webView respondsToSelector:@selector(mediaPlaybackRequiresUserAction)]) {
self.webView.mediaPlaybackRequiresUserAction = NO;
}
// By default, overscroll bouncing is allowed.
// UIWebViewBounce has been renamed to DisallowOverscroll, but both are checked.
BOOL bounceAllowed = YES;
NSNumber* disallowOverscroll = [self settingForKey:@"DisallowOverscroll"];
if (disallowOverscroll == nil) {
NSNumber* bouncePreference = [self settingForKey:@"UIWebViewBounce"];
bounceAllowed = (bouncePreference == nil || [bouncePreference boolValue]);
} else {
bounceAllowed = ![disallowOverscroll boolValue];
}
// prevent webView from bouncing
// based on the DisallowOverscroll/UIWebViewBounce key in config.xml
if (!bounceAllowed) {
if ([self.webView respondsToSelector:@selector(scrollView)]) {
((UIScrollView*)[self.webView scrollView]).bounces = NO;
((UIScrollView*)[self.wkWebView scrollView]).bounces = NO;
} else {
for (id subview in self.webView.subviews) {
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
((UIScrollView*)subview).bounces = NO;
}
}
for (id subview in self.wkWebView.subviews) {
if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {
((UIScrollView*)subview).bounces = NO;
}
}
}
}
NSString* decelerationSetting = [self settingForKey:@"UIWebViewDecelerationSpeed"];
if (![@"fast" isEqualToString : decelerationSetting]) {
[self.webView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal];
[self.wkWebView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal];
}
// don't show scrollbars
self.wkWebView.scrollView.showsHorizontalScrollIndicator = NO;
self.wkWebView.scrollView.showsVerticalScrollIndicator = NO;
/*
* iOS 6.0 UIWebView properties
*/
if (IsAtLeastiOSVersion(@"6.0")) {
BOOL keyboardDisplayRequiresUserAction = YES; // KeyboardDisplayRequiresUserAction - defaults to YES
if ([self settingForKey:@"KeyboardDisplayRequiresUserAction"] != nil) {
if ([self settingForKey:@"KeyboardDisplayRequiresUserAction"]) {
keyboardDisplayRequiresUserAction = [(NSNumber*)[self settingForKey:@"KeyboardDisplayRequiresUserAction"] boolValue];
}
}
// property check for compiling under iOS < 6
if ([self.webView respondsToSelector:@selector(setKeyboardDisplayRequiresUserAction:)]) {
[self.webView setValue:[NSNumber numberWithBool:keyboardDisplayRequiresUserAction] forKey:@"keyboardDisplayRequiresUserAction"];
}
if (!keyboardDisplayRequiresUserAction) {
[self keyboardDisplayDoesNotRequireUserAction];
}
}
/*
* iOS 7.0 UIWebView properties
*/
if (IsAtLeastiOSVersion(@"7.0")) {
SEL ios7sel = nil;
id prefObj = nil;
CGFloat gapBetweenPages = 0.0; // default
prefObj = [self settingForKey:@"GapBetweenPages"];
if (prefObj != nil) {
gapBetweenPages = [prefObj floatValue];
}
// property check for compiling under iOS < 7
ios7sel = NSSelectorFromString(@"setGapBetweenPages:");
if ([self.webView respondsToSelector:ios7sel]) {
[self.webView setValue:[NSNumber numberWithFloat:gapBetweenPages] forKey:@"gapBetweenPages"];
}
CGFloat pageLength = 0.0; // default
prefObj = [self settingForKey:@"PageLength"];
if (prefObj != nil) {
pageLength = [[self settingForKey:@"PageLength"] floatValue];
}
// property check for compiling under iOS < 7
ios7sel = NSSelectorFromString(@"setPageLength:");
if ([self.webView respondsToSelector:ios7sel]) {
[self.webView setValue:[NSNumber numberWithBool:pageLength] forKey:@"pageLength"];
}
NSInteger paginationBreakingMode = 0; // default - UIWebPaginationBreakingModePage
prefObj = [self settingForKey:@"PaginationBreakingMode"];
if (prefObj != nil) {
NSArray* validValues = @[@"page", @"column"];
NSString* prefValue = [validValues objectAtIndex:0];
if ([prefObj isKindOfClass:[NSString class]]) {
prefValue = prefObj;
}
paginationBreakingMode = [validValues indexOfObject:[prefValue lowercaseString]];
if (paginationBreakingMode == NSNotFound) {
paginationBreakingMode = 0;
}
}
// property check for compiling under iOS < 7
ios7sel = NSSelectorFromString(@"setPaginationBreakingMode:");
if ([self.webView respondsToSelector:ios7sel]) {
[self.webView setValue:[NSNumber numberWithInteger:paginationBreakingMode] forKey:@"paginationBreakingMode"];
}
NSInteger paginationMode = 0; // default - UIWebPaginationModeUnpaginated
prefObj = [self settingForKey:@"PaginationMode"];
if (prefObj != nil) {
NSArray* validValues = @[@"unpaginated", @"lefttoright", @"toptobottom", @"bottomtotop", @"righttoleft"];
NSString* prefValue = [validValues objectAtIndex:0];
if ([prefObj isKindOfClass:[NSString class]]) {
prefValue = prefObj;
}
paginationMode = [validValues indexOfObject:[prefValue lowercaseString]];
if (paginationMode == NSNotFound) {
paginationMode = 0;
}
}
// property check for compiling under iOS < 7
ios7sel = NSSelectorFromString(@"setPaginationMode:");
if ([self.webView respondsToSelector:ios7sel]) {
[self.webView setValue:[NSNumber numberWithInteger:paginationMode] forKey:@"paginationMode"];
}
}
// init startup plugins
if ([self.startupPluginNames count] > 0) {
[CDVTimer start:@"TotalPluginStartup"];
for (NSString* pluginName in self.startupPluginNames) {
[CDVTimer start:pluginName];
[self getCommandInstance:pluginName];
[CDVTimer stop:pluginName];
}
// Correct the frame, as plugins like statusbar may alter it.
// No need to check for pluginname like 'statusbar' because others may alter it too.
self.wkWebView.frame = self.webView.frame;
[CDVTimer stop:@"TotalPluginStartup"];
}
if(appURL != nil) {
[self loadURL:appURL];
} else if(!_targetExistsLocally) {
self.alreadyLoaded = true;
loadErr = [NSString stringWithFormat:@"ERROR: Start Page at '%@' was not found.",
self.startPage];
NSLog(@"%@", loadErr);
///////////////////
[CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {
_userAgentLockToken = lockToken;
[CDVUserAgentUtil setUserAgent:self.userAgent lockToken:lockToken];
NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>",
loadErr];
[self.wkWebView loadHTMLString:html baseURL:nil];
}];
} else {
// we'll load once the HTTP server starts.
}
// Start timer which periodically checks whether the app is alive
if (![self settingForKey:@"DisableCrashRecovery"] || ![[self settingForKey:@"DisableCrashRecovery"] boolValue]) {
_crashRecoveryTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recoverFromCrash) userInfo:nil repeats:YES];
}
}
- (void) copyLS:(unsigned short)httpPort
{
// Copy LS of UIWebView to WKWebView so upgrading to the new webview is less of a pain in the ..
NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* cacheFolder;
if ([[NSFileManager defaultManager] fileExistsAtPath:[appLibraryFolder stringByAppendingPathComponent:@"WebKit/LocalStorage/file__0.localstorage"]]) {
cacheFolder = [appLibraryFolder stringByAppendingPathComponent:@"WebKit/LocalStorage"];
} else {
cacheFolder = [appLibraryFolder stringByAppendingPathComponent:@"Caches"];
}
self.uiWebViewLS = [cacheFolder stringByAppendingPathComponent:@"file__0.localstorage"];
if (![self settingForKey:@"DisableLocalStorageSyncWithUIWebView"] || ![[self settingForKey:@"DisableLocalStorageSyncWithUIWebView"] boolValue]) {
// copy the localStorage DB of the old webview to the new one (it's copied back when the app is suspended/shut down)
self.wkWebViewLS = [[NSString alloc] initWithString: [appLibraryFolder stringByAppendingPathComponent:@"WebKit"]];
#if TARGET_IPHONE_SIMULATOR
// the simulutor squeezes the bundle id into the path
NSString* bundleIdentifier = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
self.wkWebViewLS = [self.wkWebViewLS stringByAppendingPathComponent:bundleIdentifier];
#endif
// TODO if the app is ever launched on a different port.. LS can't be loaded -- not worse than the previous implementation, but still
// TODO use the port, luke!
NSString *portAsString = [NSString stringWithFormat:@"%d", httpPort];
self.wkWebViewLS = [self.wkWebViewLS stringByAppendingPathComponent:[[@"WebsiteData/LocalStorage/http_localhost_" stringByAppendingString:portAsString] stringByAppendingString:@".localstorage"]];
[[CDVLocalStorage class] copyFrom:self.uiWebViewLS to:self.wkWebViewLS error:nil];
}
}
- (WKWebView*)newCordovaWKWebViewWithFrame:(CGRect)bounds wkWebViewConfig:(WKWebViewConfiguration*) config
{
WKWebView* cordovaView = [[WKWebView alloc] initWithFrame:bounds configuration:config];
NSLog(@"Using a WKWebView");
_webViewUIDelegate = [[CDVWebViewUIDelegate alloc] initWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]];
cordovaView.UIDelegate = _webViewUIDelegate;
ReroutingUIWebView *e = [[ReroutingUIWebView alloc] initWithFrame:bounds];
e.wkWebView = cordovaView;
e.viewController = self;
self.webView = e;
return cordovaView;
}
/*
#pragma mark WKNavigationDelegate implementation
// allow opening links like mailto: / tel:
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
*/
#pragma mark WKNavigationDelegate implementation
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
// It's safe to release the lock even if this is just a sub-frame that's finished loading.
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
// Hide the Top Activity THROBBER in the Battery Bar
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPageDidLoadNotification object:self.webView]];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
[CDVUserAgentUtil releaseLock:&_userAgentLockToken];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if (!navigationAction.targetFrame) {
// links with target="_blank" need to open outside the app, but WKWebView doesn't allow it currently
NSURL *url = navigationAction.request.URL;
NSLog(@"Navigating to %@", url);
UIApplication *app = [UIApplication sharedApplication];
if ([app canOpenURL:url]) {
[app openURL:url];
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
// this is by far the weirest piece of code I've produced to date (swizzling a private method)
- (void) keyboardDisplayDoesNotRequireUserAction {
SEL sel = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
Class WKContentView = NSClassFromString(@"WKContentView");
Method method = class_getInstanceMethod(WKContentView, sel);
IMP originalImp = method_getImplementation(method);
IMP imp = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
((void (*)(id, SEL, void*, BOOL, BOOL, id))originalImp)(me, sel, arg0, TRUE, arg2, arg3);
});
method_setImplementation(method, imp);
}
#pragma mark WKScriptMessageHandler implementation
#ifdef __IPHONE_8_0
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message
{
if (![message.name isEqualToString:@"cordova"]) {
return;
}
NSArray* jsonEntry = message.body; // NSString:callbackId, NSString:service, NSString:action, NSArray:args
CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];
CDV_EXEC_LOG(@"Exec(%@): Calling %@.%@", command.callbackId, command.className, command.methodName);
[self.commandQueue execute:command];
}
#endif /* ifdef __IPHONE_8_0 */
#pragma mark Color Utility
// Assumes input like "0xFF00FF00" (0xAARRGGBB).
- (UIColor *)colorFromHexString:(NSString *)hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:((rgbValue & 0xFF000000) >> 24)/255.0];
}
@end