FlutterWebviewPlugin.m 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #import "FlutterWebviewPlugin.h"
  2. static NSString *const CHANNEL_NAME = @"flutter_webview_plugin";
  3. // UIWebViewDelegate
  4. @interface FlutterWebviewPlugin() <WKNavigationDelegate, UIScrollViewDelegate> {
  5. BOOL _enableAppScheme;
  6. BOOL _enableZoom;
  7. }
  8. @end
  9. @implementation FlutterWebviewPlugin
  10. + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  11. channel = [FlutterMethodChannel
  12. methodChannelWithName:CHANNEL_NAME
  13. binaryMessenger:[registrar messenger]];
  14. UIViewController *viewController = (UIViewController *)registrar.messenger;
  15. FlutterWebviewPlugin* instance = [[FlutterWebviewPlugin alloc] initWithViewController:viewController];
  16. [registrar addMethodCallDelegate:instance channel:channel];
  17. }
  18. - (instancetype)initWithViewController:(UIViewController *)viewController {
  19. self = [super init];
  20. if (self) {
  21. self.viewController = viewController;
  22. }
  23. return self;
  24. }
  25. - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  26. if ([@"launch" isEqualToString:call.method]) {
  27. if (!self.webview)
  28. [self initWebview:call];
  29. else
  30. [self navigate:call];
  31. result(nil);
  32. } else if ([@"close" isEqualToString:call.method]) {
  33. [self closeWebView];
  34. result(nil);
  35. } else if ([@"eval" isEqualToString:call.method]) {
  36. [self evalJavascript:call completionHandler:^(NSString * response) {
  37. result(response);
  38. }];
  39. } else if ([@"resize" isEqualToString:call.method]) {
  40. [self resize:call];
  41. result(nil);
  42. } else if ([@"reloadUrl" isEqualToString:call.method]) {
  43. [self reloadUrl:call];
  44. result(nil);
  45. } else if ([@"show" isEqualToString:call.method]) {
  46. [self show];
  47. result(nil);
  48. } else if ([@"hide" isEqualToString:call.method]) {
  49. [self hide];
  50. result(nil);
  51. } else {
  52. result(FlutterMethodNotImplemented);
  53. }
  54. }
  55. - (void)initWebview:(FlutterMethodCall*)call {
  56. NSNumber *clearCache = call.arguments[@"clearCache"];
  57. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  58. NSNumber *hidden = call.arguments[@"hidden"];
  59. NSDictionary *rect = call.arguments[@"rect"];
  60. _enableAppScheme = call.arguments[@"enableAppScheme"];
  61. NSString *userAgent = call.arguments[@"userAgent"];
  62. NSNumber *withZoom = call.arguments[@"withZoom"];
  63. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  64. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  65. }
  66. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  67. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  68. }];
  69. }
  70. if (userAgent != (id)[NSNull null]) {
  71. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  72. }
  73. CGRect rc;
  74. if (rect != nil) {
  75. rc = [self parseRect:rect];
  76. } else {
  77. rc = self.viewController.view.bounds;
  78. }
  79. self.webview = [[WKWebView alloc] initWithFrame:rc];
  80. self.webview.navigationDelegate = self;
  81. self.webview.scrollView.delegate = self;
  82. self.webview.hidden = [hidden boolValue];
  83. _enableZoom = [withZoom boolValue];
  84. [self.viewController.view addSubview:self.webview];
  85. [self navigate:call];
  86. }
  87. - (CGRect)parseRect:(NSDictionary *)rect {
  88. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  89. [[rect valueForKey:@"top"] doubleValue],
  90. [[rect valueForKey:@"width"] doubleValue],
  91. [[rect valueForKey:@"height"] doubleValue]);
  92. }
  93. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  94. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  95. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  96. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  97. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  98. }
  99. - (void)navigate:(FlutterMethodCall*)call {
  100. if (self.webview != nil) {
  101. NSString *url = call.arguments[@"url"];
  102. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  103. if ( [withLocalUrl boolValue]) {
  104. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  105. if (@available(iOS 9.0, *)) {
  106. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  107. } else {
  108. @throw @"not available on version earlier than ios 9.0";
  109. }
  110. } else {
  111. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  112. [self.webview loadRequest:request];
  113. }
  114. }
  115. }
  116. - (void)evalJavascript:(FlutterMethodCall*)call
  117. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  118. if (self.webview != nil) {
  119. NSString *code = call.arguments[@"code"];
  120. [self.webview evaluateJavaScript:code
  121. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  122. completionHandler([NSString stringWithFormat:@"%@", response]);
  123. }];
  124. } else {
  125. completionHandler(nil);
  126. }
  127. }
  128. - (void)resize:(FlutterMethodCall*)call {
  129. if (self.webview != nil) {
  130. NSDictionary *rect = call.arguments[@"rect"];
  131. CGRect rc = [self parseRect:rect];
  132. self.webview.frame = rc;
  133. }
  134. }
  135. - (void)closeWebView {
  136. if (self.webview != nil) {
  137. [self.webview stopLoading];
  138. [self.webview removeFromSuperview];
  139. self.webview.navigationDelegate = nil;
  140. self.webview = nil;
  141. // manually trigger onDestroy
  142. [channel invokeMethod:@"onDestroy" arguments:nil];
  143. }
  144. }
  145. - (void)reloadUrl:(FlutterMethodCall*)call {
  146. if (self.webview != nil) {
  147. NSString *url = call.arguments[@"url"];
  148. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  149. [self.webview loadRequest:request];
  150. }
  151. }
  152. - (void)show {
  153. if (self.webview != nil) {
  154. self.webview.hidden = false;
  155. }
  156. }
  157. - (void)hide {
  158. if (self.webview != nil) {
  159. self.webview.hidden = true;
  160. }
  161. }
  162. #pragma mark -- WkWebView Delegate
  163. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  164. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  165. id data = @{@"url": navigationAction.request.URL.absoluteString,
  166. @"type": @"shouldStart",
  167. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  168. [channel invokeMethod:@"onState" arguments:data];
  169. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  170. [channel invokeMethod:@"onBackPressed" arguments:nil];
  171. } else {
  172. id data = @{@"url": navigationAction.request.URL.absoluteString};
  173. [channel invokeMethod:@"onUrlChanged" arguments:data];
  174. }
  175. if (_enableAppScheme ||
  176. ([webView.URL.scheme isEqualToString:@"http"] ||
  177. [webView.URL.scheme isEqualToString:@"https"] ||
  178. [webView.URL.scheme isEqualToString:@"about"])) {
  179. decisionHandler(WKNavigationActionPolicyAllow);
  180. } else {
  181. decisionHandler(WKNavigationActionPolicyCancel);
  182. }
  183. }
  184. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  185. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  186. }
  187. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  188. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  189. }
  190. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  191. id data = [FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", error.code]
  192. message:error.localizedDescription
  193. details:error.localizedFailureReason];
  194. [channel invokeMethod:@"onError" arguments:data];
  195. }
  196. #pragma mark -- UIScrollViewDelegate
  197. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  198. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  199. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  200. }
  201. }
  202. @end