Flutter项目webview_flutter插件设置Cookie偶现丢失

此问题只在iOS上有,Android不会出现该问题,需要通过修改第三库插件的iOS原生代码解决,修改之后库只能放到私有库引用,有大版本更新定期去合并官方库的代码就行。

1、把官方库下载放到私有库,找到插件的原生代码FWFWebViewHostApi.m文件,在createWithIdentifier方法里添加如下代码:
- (void)createWithIdentifier:(NSInteger)identifier
     configurationIdentifier:(NSInteger)configurationIdentifier
                       error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error {
  WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager
      instanceForIdentifier:configurationIdentifier];
    

    // iOS 使用自带setCookie方法会偶现丢失
    // 需要加这段代码
    if (@available(iOS 11.0, *)) {
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray *cookies = cookieStorage.cookies;
        
        WKWebsiteDataStore *dataStore = [WKWebsiteDataStore nonPersistentDataStore];
        NSInteger count = cookies.count;
        for (NSInteger i = 0; i < count; i++) {
            NSHTTPCookie *cookie = cookies[i];
            [dataStore.httpCookieStore setCookie:cookie completionHandler:nil];
        }
        configuration.websiteDataStore = dataStore;
    }
    
  FWFWebView *webView = [[FWFWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)
                                            configuration:configuration
                                          binaryMessenger:self.binaryMessenger
                                          instanceManager:self.instanceManager];
  [self.instanceManager addDartCreatedInstance:webView withIdentifier:identifier];
}
2、设置cookie不能再通过库里面的Dart方法设置

以前的方法如下:

      late WebViewCookieManager webViewCookieManager;

      WebViewCookie uid = WebViewCookie(name: "uid", value: appInfo.uid.toString(), domain: ".xxx.com");
      webViewCookieManager.setCookie(uid);

修改后设置方法,通过MethodChannel 发送method设置,在AppDelegate文件didFinishLaunchingWithOptions方法注册MethodChannel并监听method

        GeneratedPluginRegistrant.register(with: self)
        let messenger : FlutterBinaryMessenger = window?.rootViewController as! FlutterBinaryMessenger
        registerEPlugin(messenger: messenger)
        let channel = FlutterMethodChannel(name: "e_plugin", binaryMessenger: messenger)
        channel.setMethodCallHandler { [weak self] call, resultCall in
            if (call.method == "setCookie") {
                guard let dic = call.arguments as? Dictionary<String, Any> else {
                    return
                }
                guard let key = dic["cookie-key"], let value = dic["cookie-value"], let domain = dic["domain"] else {
                    return
                }
                var cookieProperties = [HTTPCookiePropertyKey: Any]()
                cookieProperties[HTTPCookiePropertyKey.name] = key
                cookieProperties[HTTPCookiePropertyKey.value] = value
                cookieProperties[HTTPCookiePropertyKey.domain] = domain
                cookieProperties[HTTPCookiePropertyKey.path] = "/"
                if let cookie = HTTPCookie(properties: cookieProperties) {
                    HTTPCookieStorage.shared.setCookie(cookie)
                }
            }
        }

在Flutter发送cookie信息到原生设置

  static const MethodChannel _channel = const MethodChannel('e_plugin');

  /* 设置cookie */
  static Future<int> setCookie(Map<String, String> map) async {
    dynamic result = await _channel.invokeMethod('setCookie', map);

    int code = 0;
    if(result != null && result is Map<dynamic, dynamic>){
      code = result['code'];
    }

    return code;
  }

   EPlugin.setCookie({"cookie-key":"uid", "cookie-value":userInfo.uid.toString(), "domain":".xxx.com"}).then((value){

   });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容