WebViewImpl-ios.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCPlatformConfig.h"
  22. // Webview not available on tvOS
  23. #if (USE_WEB_VIEW > 0) && (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_TARGET_OS_TVOS)
  24. #import <WebKit/WKWebView.h>
  25. #import <WebKit/WKUIDelegate.h>
  26. #import <WebKit/WKNavigationDelegate.h>
  27. #include "WebView-inl.h"
  28. #include "platform/CCApplication.h"
  29. #include "platform/ios/CCEAGLView-ios.h"
  30. #include "platform/CCFileUtils.h"
  31. @interface UIWebViewWrapper : NSObject
  32. @property (nonatomic) std::function<bool(std::string url)> shouldStartLoading;
  33. @property (nonatomic) std::function<void(std::string url)> didFinishLoading;
  34. @property (nonatomic) std::function<void(std::string url)> didFailLoading;
  35. @property (nonatomic) std::function<void(std::string url)> onJsCallback;
  36. @property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
  37. @property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
  38. + (instancetype)webViewWrapper;
  39. - (void)setVisible:(bool)visible;
  40. - (void)setBounces:(bool)bounces;
  41. - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height;
  42. - (void)setJavascriptInterfaceScheme:(const std::string &)scheme;
  43. - (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL;
  44. - (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL;
  45. - (void)loadUrl:(const std::string &)urlString;
  46. - (void)loadFile:(const std::string &)filePath;
  47. - (void)stopLoading;
  48. - (void)reload;
  49. - (void)evaluateJS:(const std::string &)js;
  50. - (void)goBack;
  51. - (void)goForward;
  52. - (void)setScalesPageToFit:(const bool)scalesPageToFit;
  53. - (void)setBackgroundTransparent:(const bool)isTransparent;
  54. @end
  55. @interface UIWebViewWrapper () <WKUIDelegate, WKNavigationDelegate>
  56. @property(nonatomic, assign) WKWebView *uiWebView;
  57. @property(nonatomic, copy) NSString *jsScheme;
  58. @end
  59. @implementation UIWebViewWrapper {
  60. }
  61. + (instancetype)webViewWrapper {
  62. return [[[self alloc] init] autorelease];
  63. }
  64. - (instancetype)init {
  65. self = [super init];
  66. if (self) {
  67. self.uiWebView = nil;
  68. self.shouldStartLoading = nullptr;
  69. self.didFinishLoading = nullptr;
  70. self.didFailLoading = nullptr;
  71. }
  72. return self;
  73. }
  74. - (void)dealloc {
  75. self.uiWebView.UIDelegate = nil;
  76. [self.uiWebView removeFromSuperview];
  77. [self.uiWebView release];
  78. self.jsScheme = nil;
  79. [super dealloc];
  80. }
  81. - (void)setupWebView {
  82. if (!self.uiWebView) {
  83. self.uiWebView = [[WKWebView alloc] init];
  84. self.uiWebView.UIDelegate = self;
  85. self.uiWebView.navigationDelegate = self;
  86. }
  87. if (!self.uiWebView.superview) {
  88. auto eaglview = (CCEAGLView*)cocos2d::Application::getInstance()->getView();
  89. [eaglview addSubview:self.uiWebView];
  90. }
  91. }
  92. - (void)setVisible:(bool)visible {
  93. self.uiWebView.hidden = !visible;
  94. }
  95. - (void)setBounces:(bool)bounces {
  96. self.uiWebView.scrollView.bounces = bounces;
  97. }
  98. - (void)setFrameWithX:(float)x y:(float)y width:(float)width height:(float)height {
  99. if (!self.uiWebView) {[self setupWebView];}
  100. CGRect newFrame = CGRectMake(x, y, width, height);
  101. if (!CGRectEqualToRect(self.uiWebView.frame, newFrame)) {
  102. self.uiWebView.frame = CGRectMake(x, y, width, height);
  103. }
  104. }
  105. - (void)setJavascriptInterfaceScheme:(const std::string &)scheme {
  106. self.jsScheme = @(scheme.c_str());
  107. }
  108. - (void)loadData:(const std::string &)data MIMEType:(const std::string &)MIMEType textEncodingName:(const std::string &)encodingName baseURL:(const std::string &)baseURL {
  109. auto path = [[NSBundle mainBundle] resourcePath];
  110. path = [path stringByAppendingPathComponent:@(baseURL.c_str() )];
  111. auto url = [NSURL fileURLWithPath:path];
  112. [self.uiWebView loadData:[NSData dataWithBytes:data.c_str() length:data.length()]
  113. MIMEType:@(MIMEType.c_str())
  114. characterEncodingName:@(encodingName.c_str())
  115. baseURL:url];
  116. }
  117. - (void)loadHTMLString:(const std::string &)string baseURL:(const std::string &)baseURL {
  118. if (!self.uiWebView) {[self setupWebView];}
  119. auto path = [[NSBundle mainBundle] resourcePath];
  120. path = [path stringByAppendingPathComponent:@(baseURL.c_str() )];
  121. auto url = [NSURL fileURLWithPath:path];
  122. [self.uiWebView loadHTMLString:@(string.c_str()) baseURL:url];
  123. }
  124. - (void)loadUrl:(const std::string &)urlString {
  125. if (!self.uiWebView) {[self setupWebView];}
  126. NSURL *url = [NSURL URLWithString:@(urlString.c_str())];
  127. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  128. [self.uiWebView loadRequest:request];
  129. }
  130. - (void)loadFile:(const std::string &)filePath {
  131. if (!self.uiWebView) {[self setupWebView];}
  132. NSURL *url = [NSURL fileURLWithPath:@(filePath.c_str())];
  133. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  134. [self.uiWebView loadRequest:request];
  135. }
  136. - (void)stopLoading {
  137. [self.uiWebView stopLoading];
  138. }
  139. - (void)reload {
  140. [self.uiWebView reload];
  141. }
  142. - (BOOL)canGoForward {
  143. return self.uiWebView.canGoForward;
  144. }
  145. - (BOOL)canGoBack {
  146. return self.uiWebView.canGoBack;
  147. }
  148. - (void)goBack {
  149. [self.uiWebView goBack];
  150. }
  151. - (void)goForward {
  152. [self.uiWebView goForward];
  153. }
  154. - (void)evaluateJS:(const std::string &)js {
  155. if (!self.uiWebView) {[self setupWebView];}
  156. [self.uiWebView evaluateJavaScript:@(js.c_str()) completionHandler:nil];
  157. }
  158. - (void)setScalesPageToFit:(const bool)scalesPageToFit {
  159. // TODO: there is not corresponding API in WK.
  160. // https://stackoverflow.com/questions/26295277/wkwebview-equivalent-for-uiwebviews-scalespagetofit/43048514 seems has a solution,
  161. // but it doesn't support setting it dynamically. If we want to set this feature dynamically, then it will be too complex.
  162. }
  163. - (void)setBackgroundTransparent:(const bool)isTransparent {
  164. if (!self.uiWebView) {[self setupWebView];}
  165. [self.uiWebView setOpaque:isTransparent ? NO : YES];
  166. [self.uiWebView setBackgroundColor:isTransparent ? [UIColor clearColor] : [UIColor whiteColor]];
  167. }
  168. #pragma mark - WKNavigationDelegate
  169. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  170. NSString *url = [[navigationAction request].URL.absoluteString stringByRemovingPercentEncoding];
  171. NSString* scheme = [navigationAction request].URL.scheme;
  172. if ([scheme isEqualToString:self.jsScheme]) {
  173. self.onJsCallback(url.UTF8String);
  174. decisionHandler(WKNavigationActionPolicyCancel);
  175. return;
  176. }
  177. if (self.shouldStartLoading && url) {
  178. if (self.shouldStartLoading(url.UTF8String) )
  179. decisionHandler(WKNavigationActionPolicyAllow);
  180. else
  181. decisionHandler(WKNavigationActionPolicyCancel);
  182. return;
  183. }
  184. decisionHandler(WKNavigationActionPolicyAllow);
  185. }
  186. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  187. if (self.didFinishLoading) {
  188. NSString *url = [webView.URL absoluteString];
  189. self.didFinishLoading([url UTF8String]);
  190. }
  191. }
  192. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  193. if (self.didFailLoading) {
  194. NSString *errorInfo = error.userInfo[NSURLErrorFailingURLStringErrorKey];
  195. if (errorInfo) {
  196. self.didFailLoading([errorInfo UTF8String]);
  197. }
  198. }
  199. }
  200. #pragma WKUIDelegate
  201. // Implement js alert function.
  202. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler
  203. {
  204. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
  205. message:nil
  206. preferredStyle:UIAlertControllerStyleAlert];
  207. [alertController addAction:[UIAlertAction actionWithTitle:@"Ok"
  208. style:UIAlertActionStyleCancel
  209. handler:^(UIAlertAction *action) {
  210. completionHandler();
  211. }]];
  212. auto rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
  213. [rootViewController presentViewController:alertController animated:YES completion:^{}];
  214. }
  215. @end
  216. namespace cocos2d {
  217. WebViewImpl::WebViewImpl(WebView *webView)
  218. : _uiWebViewWrapper([UIWebViewWrapper webViewWrapper]),
  219. _webView(webView) {
  220. [_uiWebViewWrapper retain];
  221. _uiWebViewWrapper.shouldStartLoading = [this](std::string url) {
  222. if (this->_webView->_onShouldStartLoading) {
  223. return this->_webView->_onShouldStartLoading(this->_webView, url);
  224. }
  225. return true;
  226. };
  227. _uiWebViewWrapper.didFinishLoading = [this](std::string url) {
  228. if (this->_webView->_onDidFinishLoading) {
  229. this->_webView->_onDidFinishLoading(this->_webView, url);
  230. }
  231. };
  232. _uiWebViewWrapper.didFailLoading = [this](std::string url) {
  233. if (this->_webView->_onDidFailLoading) {
  234. this->_webView->_onDidFailLoading(this->_webView, url);
  235. }
  236. };
  237. _uiWebViewWrapper.onJsCallback = [this](std::string url) {
  238. if (this->_webView->_onJSCallback) {
  239. this->_webView->_onJSCallback(this->_webView, url);
  240. }
  241. };
  242. }
  243. WebViewImpl::~WebViewImpl(){
  244. [_uiWebViewWrapper release];
  245. _uiWebViewWrapper = nullptr;
  246. }
  247. void WebViewImpl::setJavascriptInterfaceScheme(const std::string &scheme) {
  248. [_uiWebViewWrapper setJavascriptInterfaceScheme:scheme];
  249. }
  250. void WebViewImpl::loadData(const Data &data,
  251. const std::string &MIMEType,
  252. const std::string &encoding,
  253. const std::string &baseURL) {
  254. std::string dataString(reinterpret_cast<char *>(data.getBytes()), static_cast<unsigned int>(data.getSize()));
  255. [_uiWebViewWrapper loadData:dataString MIMEType:MIMEType textEncodingName:encoding baseURL:baseURL];
  256. }
  257. void WebViewImpl::loadHTMLString(const std::string &string, const std::string &baseURL) {
  258. [_uiWebViewWrapper loadHTMLString:string baseURL:baseURL];
  259. }
  260. void WebViewImpl::loadURL(const std::string &url) {
  261. [_uiWebViewWrapper loadUrl:url];
  262. }
  263. void WebViewImpl::loadFile(const std::string &fileName) {
  264. auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fileName);
  265. [_uiWebViewWrapper loadFile:fullPath];
  266. }
  267. void WebViewImpl::stopLoading() {
  268. [_uiWebViewWrapper stopLoading];
  269. }
  270. void WebViewImpl::reload() {
  271. [_uiWebViewWrapper reload];
  272. }
  273. bool WebViewImpl::canGoBack() {
  274. return _uiWebViewWrapper.canGoBack;
  275. }
  276. bool WebViewImpl::canGoForward() {
  277. return _uiWebViewWrapper.canGoForward;
  278. }
  279. void WebViewImpl::goBack() {
  280. [_uiWebViewWrapper goBack];
  281. }
  282. void WebViewImpl::goForward() {
  283. [_uiWebViewWrapper goForward];
  284. }
  285. void WebViewImpl::evaluateJS(const std::string &js) {
  286. [_uiWebViewWrapper evaluateJS:js];
  287. }
  288. void WebViewImpl::setBounces(bool bounces) {
  289. [_uiWebViewWrapper setBounces:bounces];
  290. }
  291. void WebViewImpl::setScalesPageToFit(const bool scalesPageToFit) {
  292. [_uiWebViewWrapper setScalesPageToFit:scalesPageToFit];
  293. }
  294. void WebViewImpl::setVisible(bool visible){
  295. [_uiWebViewWrapper setVisible:visible];
  296. }
  297. void WebViewImpl::setFrame(float x, float y, float width, float height){
  298. auto eaglview = (CCEAGLView*)cocos2d::Application::getInstance()->getView();
  299. auto scaleFactor = [eaglview contentScaleFactor];
  300. [_uiWebViewWrapper setFrameWithX:x/scaleFactor
  301. y:y/scaleFactor
  302. width:width/scaleFactor
  303. height:height/scaleFactor];
  304. }
  305. void WebViewImpl::setBackgroundTransparent(bool isTransparent){
  306. [_uiWebViewWrapper setBackgroundTransparent:isTransparent];
  307. }
  308. } //namespace cocos2d
  309. #endif // (USE_WEB_VIEW > 0) && (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_TARGET_OS_TVOS)