FlutterWebviewPlugin.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #import "FlutterWebviewPlugin.h"
  2. static NSString *const CHANNEL_NAME = @"flutter_webview_plugin";
  3. // UIWebViewDelegate
  4. @interface FlutterWebviewPlugin() <WKNavigationDelegate, UIScrollViewDelegate, WKUIDelegate> {
  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.UIDelegate = self;
  96. self.webview.navigationDelegate = self;
  97. self.webview.scrollView.delegate = self;
  98. self.webview.hidden = [hidden boolValue];
  99. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  100. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  101. _enableZoom = [withZoom boolValue];
  102. [self.viewController.view addSubview:self.webview];
  103. [self navigate:call];
  104. }
  105. - (CGRect)parseRect:(NSDictionary *)rect {
  106. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  107. [[rect valueForKey:@"top"] doubleValue],
  108. [[rect valueForKey:@"width"] doubleValue],
  109. [[rect valueForKey:@"height"] doubleValue]);
  110. }
  111. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  112. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  113. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  114. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  115. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  116. }
  117. - (void)navigate:(FlutterMethodCall*)call {
  118. if (self.webview != nil) {
  119. NSString *url = call.arguments[@"url"];
  120. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  121. if ( [withLocalUrl boolValue]) {
  122. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  123. if (@available(iOS 9.0, *)) {
  124. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  125. } else {
  126. @throw @"not available on version earlier than ios 9.0";
  127. }
  128. } else {
  129. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  130. NSDictionary *headers = call.arguments[@"headers"];
  131. if (headers != nil) {
  132. [request setAllHTTPHeaderFields:headers];
  133. }
  134. [self.webview loadRequest:request];
  135. }
  136. }
  137. }
  138. - (void)evalJavascript:(FlutterMethodCall*)call
  139. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  140. if (self.webview != nil) {
  141. NSString *code = call.arguments[@"code"];
  142. [self.webview evaluateJavaScript:code
  143. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  144. completionHandler([NSString stringWithFormat:@"%@", response]);
  145. }];
  146. } else {
  147. completionHandler(nil);
  148. }
  149. }
  150. - (void)resize:(FlutterMethodCall*)call {
  151. if (self.webview != nil) {
  152. NSDictionary *rect = call.arguments[@"rect"];
  153. CGRect rc = [self parseRect:rect];
  154. self.webview.frame = rc;
  155. }
  156. }
  157. - (void)closeWebView {
  158. if (self.webview != nil) {
  159. [self.webview stopLoading];
  160. [self.webview removeFromSuperview];
  161. self.webview.navigationDelegate = nil;
  162. self.webview = nil;
  163. // manually trigger onDestroy
  164. [channel invokeMethod:@"onDestroy" arguments:nil];
  165. }
  166. }
  167. - (void)reloadUrl:(FlutterMethodCall*)call {
  168. if (self.webview != nil) {
  169. NSString *url = call.arguments[@"url"];
  170. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  171. [self.webview loadRequest:request];
  172. }
  173. }
  174. - (void)show {
  175. if (self.webview != nil) {
  176. self.webview.hidden = false;
  177. }
  178. }
  179. - (void)hide {
  180. if (self.webview != nil) {
  181. self.webview.hidden = true;
  182. }
  183. }
  184. - (void)stopLoading {
  185. if (self.webview != nil) {
  186. [self.webview stopLoading];
  187. }
  188. }
  189. - (void)back {
  190. if (self.webview != nil) {
  191. [self.webview goBack];
  192. }
  193. }
  194. - (void)forward {
  195. if (self.webview != nil) {
  196. [self.webview goForward];
  197. }
  198. }
  199. - (void)reload {
  200. if (self.webview != nil) {
  201. [self.webview reload];
  202. }
  203. }
  204. - (void)cleanCookies {
  205. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  206. }];
  207. }
  208. #pragma mark -- WkWebView Delegate
  209. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  210. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  211. id data = @{@"url": navigationAction.request.URL.absoluteString,
  212. @"type": @"shouldStart",
  213. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  214. [channel invokeMethod:@"onState" arguments:data];
  215. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  216. [channel invokeMethod:@"onBackPressed" arguments:nil];
  217. } else {
  218. id data = @{@"url": navigationAction.request.URL.absoluteString};
  219. [channel invokeMethod:@"onUrlChanged" arguments:data];
  220. }
  221. if (_enableAppScheme ||
  222. ([webView.URL.scheme isEqualToString:@"http"] ||
  223. [webView.URL.scheme isEqualToString:@"https"] ||
  224. [webView.URL.scheme isEqualToString:@"about"])) {
  225. decisionHandler(WKNavigationActionPolicyAllow);
  226. } else {
  227. decisionHandler(WKNavigationActionPolicyCancel);
  228. }
  229. }
  230. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  231. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  232. if (!navigationAction.targetFrame.isMainFrame) {
  233. [webView loadRequest:navigationAction.request];
  234. }
  235. return nil;
  236. }
  237. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  238. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  239. }
  240. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  241. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  242. }
  243. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  244. [channel invokeMethod:@"onError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  245. }
  246. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  247. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  248. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  249. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  250. }
  251. decisionHandler(WKNavigationResponsePolicyAllow);
  252. }
  253. #pragma mark -- UIScrollViewDelegate
  254. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  255. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  256. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  257. }
  258. }
  259. @end