FlutterWebviewPlugin.m 10 KB

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