FlutterWebviewPlugin.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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)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. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  112. NSDictionary *headers = call.arguments[@"headers"];
  113. if (headers != nil) {
  114. [request setAllHTTPHeaderFields:headers];
  115. }
  116. [self.webview loadRequest:request];
  117. }
  118. }
  119. }
  120. - (void)evalJavascript:(FlutterMethodCall*)call
  121. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  122. if (self.webview != nil) {
  123. NSString *code = call.arguments[@"code"];
  124. [self.webview evaluateJavaScript:code
  125. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  126. completionHandler([NSString stringWithFormat:@"%@", response]);
  127. }];
  128. } else {
  129. completionHandler(nil);
  130. }
  131. }
  132. - (void)resize:(FlutterMethodCall*)call {
  133. if (self.webview != nil) {
  134. NSDictionary *rect = call.arguments[@"rect"];
  135. CGRect rc = [self parseRect:rect];
  136. self.webview.frame = rc;
  137. }
  138. }
  139. - (void)closeWebView {
  140. if (self.webview != nil) {
  141. [self.webview stopLoading];
  142. [self.webview removeFromSuperview];
  143. self.webview.navigationDelegate = nil;
  144. self.webview = nil;
  145. // manually trigger onDestroy
  146. [channel invokeMethod:@"onDestroy" arguments:nil];
  147. }
  148. }
  149. - (void)reloadUrl:(FlutterMethodCall*)call {
  150. if (self.webview != nil) {
  151. NSString *url = call.arguments[@"url"];
  152. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  153. [self.webview loadRequest:request];
  154. }
  155. }
  156. - (void)show {
  157. if (self.webview != nil) {
  158. self.webview.hidden = false;
  159. }
  160. }
  161. - (void)hide {
  162. if (self.webview != nil) {
  163. self.webview.hidden = true;
  164. }
  165. }
  166. - (void)stopLoading {
  167. if (self.webview != nil) {
  168. [self.webview stopLoading];
  169. }
  170. }
  171. #pragma mark -- WkWebView Delegate
  172. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  173. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  174. id data = @{@"url": navigationAction.request.URL.absoluteString,
  175. @"type": @"shouldStart",
  176. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  177. [channel invokeMethod:@"onState" arguments:data];
  178. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  179. [channel invokeMethod:@"onBackPressed" arguments:nil];
  180. } else {
  181. id data = @{@"url": navigationAction.request.URL.absoluteString};
  182. [channel invokeMethod:@"onUrlChanged" arguments:data];
  183. }
  184. if (_enableAppScheme ||
  185. ([webView.URL.scheme isEqualToString:@"http"] ||
  186. [webView.URL.scheme isEqualToString:@"https"] ||
  187. [webView.URL.scheme isEqualToString:@"about"])) {
  188. decisionHandler(WKNavigationActionPolicyAllow);
  189. } else {
  190. decisionHandler(WKNavigationActionPolicyCancel);
  191. }
  192. }
  193. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  194. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  195. }
  196. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  197. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  198. }
  199. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  200. id data = [FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", error.code]
  201. message:error.localizedDescription
  202. details:error.localizedFailureReason];
  203. [channel invokeMethod:@"onError" arguments:data];
  204. }
  205. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  206. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  207. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  208. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  209. }
  210. decisionHandler(WKNavigationResponsePolicyAllow);
  211. }
  212. #pragma mark -- UIScrollViewDelegate
  213. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  214. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  215. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  216. }
  217. }
  218. @end