FlutterWebviewPlugin.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 if ([@"stopLoading" isEqualToString:call.method]) {
  52. [self stopLoading];
  53. result(nil);
  54. } else {
  55. result(FlutterMethodNotImplemented);
  56. }
  57. }
  58. - (void)initWebview:(FlutterMethodCall*)call {
  59. NSNumber *clearCache = call.arguments[@"clearCache"];
  60. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  61. NSNumber *hidden = call.arguments[@"hidden"];
  62. NSDictionary *rect = call.arguments[@"rect"];
  63. _enableAppScheme = call.arguments[@"enableAppScheme"];
  64. NSString *userAgent = call.arguments[@"userAgent"];
  65. NSNumber *withZoom = call.arguments[@"withZoom"];
  66. NSNumber *scrollBar = call.arguments[@"scrollBar"];
  67. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  68. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  69. }
  70. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  71. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  72. }];
  73. }
  74. if (userAgent != (id)[NSNull null]) {
  75. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  76. }
  77. CGRect rc;
  78. if (rect != nil) {
  79. rc = [self parseRect:rect];
  80. } else {
  81. rc = self.viewController.view.bounds;
  82. }
  83. self.webview = [[WKWebView alloc] initWithFrame:rc];
  84. self.webview.navigationDelegate = self;
  85. self.webview.scrollView.delegate = self;
  86. self.webview.hidden = [hidden boolValue];
  87. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  88. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  89. _enableZoom = [withZoom boolValue];
  90. [self.viewController.view addSubview:self.webview];
  91. [self navigate:call];
  92. }
  93. - (CGRect)parseRect:(NSDictionary *)rect {
  94. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  95. [[rect valueForKey:@"top"] doubleValue],
  96. [[rect valueForKey:@"width"] doubleValue],
  97. [[rect valueForKey:@"height"] doubleValue]);
  98. }
  99. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  100. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  101. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  102. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  103. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  104. }
  105. - (void)navigate:(FlutterMethodCall*)call {
  106. if (self.webview != nil) {
  107. NSString *url = call.arguments[@"url"];
  108. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  109. if ( [withLocalUrl boolValue]) {
  110. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  111. if (@available(iOS 9.0, *)) {
  112. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  113. } else {
  114. @throw @"not available on version earlier than ios 9.0";
  115. }
  116. } else {
  117. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  118. NSDictionary *headers = call.arguments[@"headers"];
  119. if (headers != nil) {
  120. [request setAllHTTPHeaderFields:headers];
  121. }
  122. [self.webview loadRequest:request];
  123. }
  124. }
  125. }
  126. - (void)evalJavascript:(FlutterMethodCall*)call
  127. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  128. if (self.webview != nil) {
  129. NSString *code = call.arguments[@"code"];
  130. [self.webview evaluateJavaScript:code
  131. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  132. completionHandler([NSString stringWithFormat:@"%@", response]);
  133. }];
  134. } else {
  135. completionHandler(nil);
  136. }
  137. }
  138. - (void)resize:(FlutterMethodCall*)call {
  139. if (self.webview != nil) {
  140. NSDictionary *rect = call.arguments[@"rect"];
  141. CGRect rc = [self parseRect:rect];
  142. self.webview.frame = rc;
  143. }
  144. }
  145. - (void)closeWebView {
  146. if (self.webview != nil) {
  147. [self.webview stopLoading];
  148. [self.webview removeFromSuperview];
  149. self.webview.navigationDelegate = nil;
  150. self.webview = nil;
  151. // manually trigger onDestroy
  152. [channel invokeMethod:@"onDestroy" arguments:nil];
  153. }
  154. }
  155. - (void)reloadUrl:(FlutterMethodCall*)call {
  156. if (self.webview != nil) {
  157. NSString *url = call.arguments[@"url"];
  158. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  159. [self.webview loadRequest:request];
  160. }
  161. }
  162. - (void)show {
  163. if (self.webview != nil) {
  164. self.webview.hidden = false;
  165. }
  166. }
  167. - (void)hide {
  168. if (self.webview != nil) {
  169. self.webview.hidden = true;
  170. }
  171. }
  172. - (void)stopLoading {
  173. if (self.webview != nil) {
  174. [self.webview stopLoading];
  175. }
  176. }
  177. #pragma mark -- WkWebView Delegate
  178. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  179. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  180. id data = @{@"url": navigationAction.request.URL.absoluteString,
  181. @"type": @"shouldStart",
  182. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  183. [channel invokeMethod:@"onState" arguments:data];
  184. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  185. [channel invokeMethod:@"onBackPressed" arguments:nil];
  186. } else {
  187. id data = @{@"url": navigationAction.request.URL.absoluteString};
  188. [channel invokeMethod:@"onUrlChanged" arguments:data];
  189. }
  190. if (_enableAppScheme ||
  191. ([webView.URL.scheme isEqualToString:@"http"] ||
  192. [webView.URL.scheme isEqualToString:@"https"] ||
  193. [webView.URL.scheme isEqualToString:@"about"])) {
  194. decisionHandler(WKNavigationActionPolicyAllow);
  195. } else {
  196. decisionHandler(WKNavigationActionPolicyCancel);
  197. }
  198. }
  199. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  200. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  201. }
  202. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  203. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  204. }
  205. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  206. id data = [FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", error.code]
  207. message:error.localizedDescription
  208. details:error.localizedFailureReason];
  209. [channel invokeMethod:@"onError" arguments:data];
  210. }
  211. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  212. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  213. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  214. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  215. }
  216. decisionHandler(WKNavigationResponsePolicyAllow);
  217. }
  218. #pragma mark -- UIScrollViewDelegate
  219. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  220. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  221. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  222. }
  223. }
  224. @end