Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

breaking: Use WKURLSchemeHandler for serving app content #781

Merged
merged 7 commits into from
Feb 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ - (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName names

- (void)parserDidStartDocument:(NSXMLParser*)parser
{
NSString* scheme = [NSString stringWithFormat:@"%@://",((CDVViewController*)self.viewController).appScheme];
// file: url <allow-navigations> are added by default
self.allowNavigations = [[NSMutableArray alloc] initWithArray:@[ @"file://" ]];
// navigation to the scheme used by the app is also allowed
self.allowNavigations = [[NSMutableArray alloc] initWithArray:@[ @"file://", scheme ]];
// no intents are added by default
self.allowIntents = [[NSMutableArray alloc] init];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Licensed to the Apache Software Foundation (ASF) under one
#import "CDVWebViewUIDelegate.h"
#import "CDVWebViewProcessPoolFactory.h"
#import <Cordova/NSDictionary+CordovaPreferences.h>
#import "CDVURLSchemeHandler.h"

#import <objc/message.h>

Expand All @@ -41,6 +42,8 @@ @interface CDVWebViewEngine ()
@property (nonatomic, strong, readwrite) UIView* engineWebView;
@property (nonatomic, strong, readwrite) id <WKUIDelegate> uiDelegate;
@property (nonatomic, weak) id <WKScriptMessageHandler> weakScriptMessageHandler;
@property (nonatomic, strong) CDVURLSchemeHandler * schemeHandler;
@property (nonatomic, readwrite) NSString *CDV_ASSETS_URL;

@end

Expand Down Expand Up @@ -83,26 +86,44 @@ - (WKWebViewConfiguration*) createConfigurationFromSettings:(NSDictionary*)setti
- (void)pluginInitialize
{
// viewController would be available now. we attempt to set all possible delegates to it, by default
CDVViewController* vc = (CDVViewController*)self.viewController;
NSDictionary* settings = self.commandDelegate.settings;

NSString *hostname = [settings cordovaSettingForKey:@"hostname"];
if(hostname == nil){
hostname = @"localhost";
}
NSString *scheme = [settings cordovaSettingForKey:@"scheme"];
if(scheme == nil || [WKWebView handlesURLScheme:scheme]){
scheme = @"app";
}
vc.appScheme = scheme;
self.CDV_ASSETS_URL = [NSString stringWithFormat:@"%@://%@", scheme, hostname];

self.uiDelegate = [[CDVWebViewUIDelegate alloc] initWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]];

CDVWebViewWeakScriptMessageHandler *weakScriptMessageHandler = [[CDVWebViewWeakScriptMessageHandler alloc] initWithScriptMessageHandler:self];

WKUserContentController* userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:weakScriptMessageHandler name:CDV_BRIDGE_NAME];
NSString * scriptCode = [NSString stringWithFormat:@"window.CDV_ASSETS_URL = '%@';", self.CDV_ASSETS_URL];
WKUserScript *wkScript =
[[WKUserScript alloc] initWithSource:scriptCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
if (wkScript) {
[userContentController addUserScript:wkScript];
}

WKWebViewConfiguration* configuration = [self createConfigurationFromSettings:settings];
configuration.userContentController = userContentController;

self.schemeHandler = [[CDVURLSchemeHandler alloc] initWithVC:vc];
[configuration setURLSchemeHandler:self.schemeHandler forURLScheme:scheme];
// re-create WKWebView, since we need to update configuration
WKWebView* wkWebView = [[WKWebView alloc] initWithFrame:self.engineWebView.frame configuration:configuration];
wkWebView.UIDelegate = self.uiDelegate;
self.engineWebView = wkWebView;

if (IsAtLeastiOSVersion(@"9.0") && [self.viewController isKindOfClass:[CDVViewController class]]) {
wkWebView.customUserAgent = ((CDVViewController*) self.viewController).userAgent;
}
wkWebView.customUserAgent = vc.userAgent;

if ([self.viewController conformsToProtocol:@protocol(WKUIDelegate)]) {
wkWebView.UIDelegate = (id <WKUIDelegate>)self.viewController;
Expand Down Expand Up @@ -191,12 +212,21 @@ - (id)loadRequest:(NSURLRequest*)request
{
if ([self canLoadRequest:request]) { // can load, differentiate between file urls and other schemes
if (request.URL.fileURL) {
SEL wk_sel = NSSelectorFromString(CDV_WKWEBVIEW_FILE_URL_LOAD_SELECTOR);
NSURL* readAccessUrl = [request.URL URLByDeletingLastPathComponent];
return ((id (*)(id, SEL, id, id))objc_msgSend)(_engineWebView, wk_sel, request.URL, readAccessUrl);
} else {
return [(WKWebView*)_engineWebView loadRequest:request];
NSURL* startURL = [NSURL URLWithString:((CDVViewController *)self.viewController).startPage];
NSString* startFilePath = [self.commandDelegate pathForResource:[startURL path]];
NSURL *url = [[NSURL URLWithString:self.CDV_ASSETS_URL] URLByAppendingPathComponent:request.URL.path];
if ([request.URL.path isEqualToString:startFilePath]) {
url = [NSURL URLWithString:self.CDV_ASSETS_URL];
}
if(request.URL.query) {
url = [NSURL URLWithString:[@"?" stringByAppendingString:request.URL.query] relativeToURL:url];
}
if(request.URL.fragment) {
url = [NSURL URLWithString:[@"#" stringByAppendingString:request.URL.fragment] relativeToURL:url];
}
request = [NSURLRequest requestWithURL:url];
}
return [(WKWebView*)_engineWebView loadRequest:request];
} else { // can't load, print out error
NSString* errorHtml = [NSString stringWithFormat:
@"<!doctype html>"
Expand Down
32 changes: 32 additions & 0 deletions CordovaLib/Classes/Public/CDVURLSchemeHandler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
#import "CDVViewController.h"


@interface CDVURLSchemeHandler : NSObject <WKURLSchemeHandler>

@property (nonatomic, strong) CDVViewController* viewController;

- (instancetype)initWithVC:(CDVViewController *)controller;


@end
108 changes: 108 additions & 0 deletions CordovaLib/Classes/Public/CDVURLSchemeHandler.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/


#import "CDVURLSchemeHandler.h"
#import <MobileCoreServices/MobileCoreServices.h>

@implementation CDVURLSchemeHandler


- (instancetype)initWithVC:(CDVViewController *)controller
{
self = [super init];
if (self) {
_viewController = controller;
}
return self;
}

- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask
{
NSString * startPath = [[NSBundle mainBundle] pathForResource:self.viewController.wwwFolderName ofType: nil];
NSURL * url = urlSchemeTask.request.URL;
NSString * stringToLoad = url.path;
NSString * scheme = url.scheme;

if ([scheme isEqualToString:self.viewController.appScheme]) {
if ([stringToLoad hasPrefix:@"/_app_file_"]) {
startPath = [stringToLoad stringByReplacingOccurrencesOfString:@"/_app_file_" withString:@""];
} else {
if ([stringToLoad isEqualToString:@""] || [url.pathExtension isEqualToString:@""]) {
startPath = [startPath stringByAppendingPathComponent:self.viewController.startPage];
} else {
startPath = [startPath stringByAppendingPathComponent:stringToLoad];
}
}
}

NSError * fileError = nil;
NSData * data = nil;
if ([self isMediaExtension:url.pathExtension]) {
data = [NSData dataWithContentsOfFile:startPath options:NSDataReadingMappedIfSafe error:&fileError];
}
if (!data || fileError) {
data = [[NSData alloc] initWithContentsOfFile:startPath];
}
NSInteger statusCode = 200;
if (!data) {
statusCode = 404;
}
NSURL * localUrl = [NSURL URLWithString:url.absoluteString];
NSString * mimeType = [self getMimeType:url.pathExtension];
id response = nil;
if (data && [self isMediaExtension:url.pathExtension]) {
response = [[NSURLResponse alloc] initWithURL:localUrl MIMEType:mimeType expectedContentLength:data.length textEncodingName:nil];
} else {
NSDictionary * headers = @{ @"Content-Type" : mimeType, @"Cache-Control": @"no-cache"};
response = [[NSHTTPURLResponse alloc] initWithURL:localUrl statusCode:statusCode HTTPVersion:nil headerFields:headers];
}

[urlSchemeTask didReceiveResponse:response];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];

}

- (void)webView:(nonnull WKWebView *)webView stopURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask
{

}

-(NSString *) getMimeType:(NSString *)fileExtension {
if (fileExtension && ![fileExtension isEqualToString:@""]) {
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
return contentType ? contentType : @"application/octet-stream";
} else {
return @"text/html";
}
}

-(BOOL) isMediaExtension:(NSString *) pathExtension {
NSArray * mediaExtensions = @[@"m4v", @"mov", @"mp4",
@"aac", @"ac3", @"aiff", @"au", @"flac", @"m4a", @"mp3", @"wav"];
if ([mediaExtensions containsObject:pathExtension.lowercaseString]) {
return YES;
}
return NO;
}


@end
1 change: 1 addition & 0 deletions CordovaLib/Classes/Public/CDVViewController.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
@property (nonatomic, readonly, strong) NSMutableDictionary* settings;
@property (nonatomic, readonly, strong) NSXMLParser* configParser;

@property (nonatomic, readwrite, copy) NSString* appScheme;
@property (nonatomic, readwrite, copy) NSString* configFile;
@property (nonatomic, readwrite, copy) NSString* wwwFolderName;
@property (nonatomic, readwrite, copy) NSString* startPage;
Expand Down
8 changes: 8 additions & 0 deletions CordovaLib/CordovaLib.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
/* Begin PBXBuildFile section */
28BFF9141F355A4E00DDF01A /* CDVLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 28BFF9121F355A4E00DDF01A /* CDVLogger.h */; };
28BFF9151F355A4E00DDF01A /* CDVLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 28BFF9131F355A4E00DDF01A /* CDVLogger.m */; };
2F4D42BC23F218BA00501999 /* CDVURLSchemeHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */; };
2F4D42BD23F218BA00501999 /* CDVURLSchemeHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */; };
3093E2231B16D6A3003F381A /* CDVIntentAndNavigationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */; };
3093E2241B16D6A3003F381A /* CDVIntentAndNavigationFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */; };
4E23F8FB23E16E96006CD852 /* CDVWebViewProcessPoolFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E23F8F523E16E96006CD852 /* CDVWebViewProcessPoolFactory.m */; };
Expand Down Expand Up @@ -116,6 +118,8 @@
/* Begin PBXFileReference section */
28BFF9121F355A4E00DDF01A /* CDVLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLogger.h; sourceTree = "<group>"; };
28BFF9131F355A4E00DDF01A /* CDVLogger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLogger.m; sourceTree = "<group>"; };
2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CDVURLSchemeHandler.h; sourceTree = "<group>"; };
2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CDVURLSchemeHandler.m; sourceTree = "<group>"; };
3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVIntentAndNavigationFilter.h; sourceTree = "<group>"; };
3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVIntentAndNavigationFilter.m; sourceTree = "<group>"; };
4E23F8F523E16E96006CD852 /* CDVWebViewProcessPoolFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWebViewProcessPoolFactory.m; sourceTree = "<group>"; };
Expand Down Expand Up @@ -317,6 +321,8 @@
7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */,
7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */,
7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */,
2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */,
2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */,
);
name = Public;
path = Classes/Public;
Expand Down Expand Up @@ -393,6 +399,7 @@
7ED95D3D1AB9029B008C4574 /* CDVCommandQueue.h in Headers */,
4E23F8FF23E16E96006CD852 /* CDVWebViewProcessPoolFactory.h in Headers */,
7ED95D3F1AB9029B008C4574 /* CDVConfigParser.h in Headers */,
2F4D42BC23F218BA00501999 /* CDVURLSchemeHandler.h in Headers */,
7ED95D411AB9029B008C4574 /* CDVInvokedUrlCommand.h in Headers */,
7ED95D431AB9029B008C4574 /* CDVPlugin+Resources.h in Headers */,
7ED95D451AB9029B008C4574 /* CDVPlugin.h in Headers */,
Expand Down Expand Up @@ -529,6 +536,7 @@
7ED95D401AB9029B008C4574 /* CDVConfigParser.m in Sources */,
7ED95D421AB9029B008C4574 /* CDVInvokedUrlCommand.m in Sources */,
7ED95D441AB9029B008C4574 /* CDVPlugin+Resources.m in Sources */,
2F4D42BD23F218BA00501999 /* CDVURLSchemeHandler.m in Sources */,
7ED95D461AB9029B008C4574 /* CDVPlugin.m in Sources */,
7ED95D481AB9029B008C4574 /* CDVPluginResult.m in Sources */,
7ED95D4B1AB9029B008C4574 /* CDVTimer.m in Sources */,
Expand Down
12 changes: 12 additions & 0 deletions CordovaLib/cordova.js
Original file line number Diff line number Diff line change
Expand Up @@ -1765,6 +1765,18 @@ var exec = require('cordova/exec');
var WkWebKit = {
allowsBackForwardNavigationGestures: function (allow) {
exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);
},
convertFilePath: function (path) {
if (!path) {
return path;
}
if (path.startsWith('/')) {
return window.CDV_ASSETS_URL + '/_app_file_' + path;
}
if (path.startsWith('file://')) {
return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');
}
return path;
}
};

Expand Down
12 changes: 12 additions & 0 deletions cordova-js-src/plugin/ios/wkwebkit.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ var exec = require('cordova/exec');
var WkWebKit = {
allowsBackForwardNavigationGestures: function (allow) {
exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);
},
convertFilePath: function (path) {
if (!path) {
return path;
}
if (path.startsWith('/')) {
return window.CDV_ASSETS_URL + '/_app_file_' + path;
}
if (path.startsWith('file://')) {
return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');
}
return path;
}
};

Expand Down