当前位置:  开发笔记 > 编程语言 > 正文

是否可以使用sharedHTTPCookieStorage为UIWebView手动设置cookie?

如何解决《是否可以使用sharedHTTPCookieStorage为UIWebView手动设置cookie?》经验,为你挑选了3个好方法。

我在iOS应用程序中有Web视图,需要对身份验证cookie进行适当的身份验证.我正在寻找一种在iOS应用程序的webview中设置cookie的方法,而不必发出设置cookie的出站请求,因为我已经在客户端上有auth信息.

这篇文章向我们展示了UIWebView cookie的存储位置.

现在我正在加载一个隐藏的Web视图来发出一个出站请求,但是我不想做一个外部请求来设置一个简单的cookie.



1> kball..:

是的,你可以这样做.首先,在applicationDidBecomeActive中添加此行

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

cookieAcceptPolicy是跨应用程序共享的,可以在您不知情的情况下进行更改,因此您希望确保每次运行应用程序时都拥有所需的接受策略.

然后,设置cookie:

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

此cookie的名称为testCookie,值为someValue123456,并将随任何http请求一起发送到www.example.com.

有关设置cookie的一个重要提示,请在此处查看我的问题!

NSHTTPCookieStorage状态未保存在应用程序出口上.那里有任何明确的知识/文献?


Cookie与webview无关,它与对特定URL的HTTP请求相关联.任何HTTP请求,无论是直接来自您的代码还是来自Webview,都将使用存储在NSHTTPCookieStorage中的任何内容
有人可以确认这仍然有效吗?我在NSHTTPCookieStorage中有cookie,但是我的UIWebView中运行的javascript似乎没有它们.我使用Safari的网络检查器查看了cookie商店,它是空的.任何帮助非常感谢.iOS 10.3

2> more tension..:

编辑:适应编辑过的问题

NSHTTPCookieStorage有一个-setCookies:forURL:mainDocumentURL:方法,所以最简单的方法是使用NSURLConnection和实现-connection:didReceiveResponse:,提取cookie并将它们填充到cookie jar中:

- ( void )connection: (NSURLConnection *)connection
          didReceiveResponse: (NSURLResponse *)response
{
    NSHTTPURLResponse        *httpResponse = (NSHTTPURLResponse *)response;
    NSArray                  *cookies;

    cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields:
                             [ httpResponse allHeaderFields ]];
    [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
            setCookies: cookies forURL: self.url mainDocumentURL: nil ];
}

(你也可以简单地提取NSDictionary从对象NSHTTPCookieproperties,然后写字典中的磁盘.读它放回就像使用一样方便NSDictionary-dictionaryWithContentsOfFile:,然后创建与cookie -initWithProperties:).

然后,您可以在需要时将cookie从存储中拉出来:

- ( void )reloadWebview: (id)sender
{
    NSArray                 *cookies;
    NSDictionary            *cookieHeaders;
    NSMutableURLRequest     *request;

    cookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
                cookiesForURL: self.url ];
    if ( !cookies ) {
        /* kick off new NSURLConnection to retrieve new auth cookie */
        return;
    }

    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies ];
    request = [[ NSMutableURLRequest alloc ] initWithURL: self.url ];
    [ request setValue: [ cookieHeaders objectForKey: @"Cookie" ]
              forHTTPHeaderField: @"Cookie" ];

    [ self.webView loadRequest: request ];
    [ request release ];
}



3> JAL..:

在Swift 3中,所有键都包含在HTTPCookiePropertyKey结构中:

let cookieProperties: [HTTPCookiePropertyKey : Any] = [.name : "name",
                                                       .value : "value",
                                                       .domain : "www.example.com",
                                                       .originURL : "www.example.com",
                                                       .path : "/",
                                                       .version : "0",
                                                       .expires : Date().addingTimeInterval(2629743)
                                                      ]

if let cookie = HTTPCookie(properties: cookieProperties) {
    HTTPCookieStorage.shared.setCookie(cookie)
}

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有