我正在使用WebViewRenderer设置cookie策略,并使用来自HTTPClient的登录请求共享cookie。事实证明,就像我给出的那样:
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
在iphone模拟器中调试并运行webview时,浏览器会指示未启用Cookie策略,因此用户无法登录,因为webview从安全环境运行iframe。以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Projeto.Custom;
using Projeto.iOS.Renderers;
using Xamarin.Forms.Platform.iOS;
using WebKit;
using System.IO;
using System.Net;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace Mynamespace.iOS.Renderers
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if(Control == null)
{
var userController = new WKUserContentController();
var config = new WKWebViewConfiguration {
UserContentController = userController };
var webView = new WKWebView(Frame, config);
SetNativeControl(webView);
}
if(e.OldElement != null)
{
var hybrid = e.OldElement as CustomWebView;
hybrid.Cleanup();
}
if(e.NewElement != null)
{
var baseUrl = new NSUrl(NSBundle.MainBundle.BundlePath,
true);
string content = Element.Uri;
Control.LoadHtmlString(content, baseUrl);
var cookieUrl = new
Uri("https://secure.gooddata.com/gdc/account/login");
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies =
CustomCookie.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie)jCookie
into netCookie
select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
}
}
}
}
如果有人能告诉我在ios原生WebView中启用cookie策略的最佳方法,我将不胜感激。