【发布时间】:2018-11-05 10:04:34
【问题描述】:
我想在 Xamain iOS 中使用 WebClient 实现下载 pdf 文档功能。目前它非常适合 iOS 11,我正在使用 HttpCookieStore 获取 cookie。 对于 iOS 10,我无法检索 cookie。
处理此问题的流程是 1. 获取 cookie 2. 创建 Web 客户端服务器请求,并将 cookie 添加到标头中。
对于 iOS 11, 以下是获取 cookie 的语法:
NSHttpCookie[] cookieStoreData;
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
var cookieStore = webView.Configuration.WebsiteDataStore.HttpCookieStore;
cookieStoreData = await cookieStore.GetAllCookiesAsync();
}
对于 iOS 10,
cookieStoreData = NSHttpCookieStorage.SharedStorage.Cookies;
在这些情况下它不会返回任何 cookie,因此下一次调用 webclient 到服务器会失败(在 iOS 10 的情况下)。
StringBuilder cookies = new StringBuilder();
var webClient = new WebClient ();
foreach (var temp in cookieStoreData)
{
cookies.Append(temp.Name + "=" + temp.Value + ";");
}
webClient.Headers.Add(HttpRequestHeader.Cookie, cookies.ToString());
webClient.DownloadDataAsync (webView.Url);
webClient.DownloadDataCompleted += (s, e) => {
if (e.Error == null)
{
// Downloading data......
}
else
{
Console.WriteLine("URL for page : " + e.Error.GetType());
Console.WriteLine("URL for page : " + e.Error);
new UIAlertView("Done", "Download Failed. Please try again.", null, "OK", null).Show();
}
【问题讨论】:
-
你想从哪里获取cookies?在UIWebview、WKWebview或者一些URL请求比如AFNetworking?
-
@LucasZhang-MSFT 这是 WKWebView。现在我可以使用决定策略方法检索 cookie,但与 HttpCookieStore 相比,我无法获得完整的 cookie 列表
-
获取 cookie:[Export("webView:decidePolicyForNavigationResponse:decisionHandler:")] public void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action
decisionHandler) { NSHttpUrlResponse response; response = (NSHttpUrlResponse)navigationResponse.Response; cookies_holder = NSHttpCookie.CookiesWithResponseHeaderFields(response.AllHeaderFields, webView.Url);决策处理程序(WKNavigationResponsePolicy.Allow); }
标签: xamarin cookies xamarin.ios uiwebview webclient