FlutterWebviewPlugin.m 10 KB

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