How to delete WKWebview cookies

后端 未结 13 1538
北荒
北荒 2020-11-27 04:18

For now I am doing like this

    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [         


        
13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 04:55

    In WKWebView having issue to write and read its taking some time , So when you fetch the cookie some time you will get updated cookie but sometime it will be old one, and you will get error on any server request. I was facing this issue in 3 Days ,

    Solution: No need to store cookies in WKWebsiteDataStore.

    Getting cookies:

    Swift:

    extension WKWebView {
    private var httpCookieStore: WKHTTPCookieStore  { return WKWebsiteDataStore.default().httpCookieStore }
    func getCookies(for domain: String? = nil, completion: @escaping ([String : Any])->())  {
            var cookieDict = [String : AnyObject]()
            httpCookieStore.getAllCookies { cookies in
                for cookie in cookies {
                    if let domain = domain {
                        if cookie.domain.contains(domain) {
                            cookieDict[cookie.name] = cookie.properties as AnyObject?
                        }
                    } else {
                        cookieDict[cookie.name] = cookie.properties as AnyObject?
                    }
                }
                completion(cookieDict)
            }
        }
    }
    

    Objective-c :

    -(void )getAllCookies
    {
        NSMutableString *updatedCockies= [[NSMutableString alloc] init];
        if (@available(iOS 11.0, *)) {
            WKHTTPCookieStore *cookieStore = _webView.configuration.websiteDataStore.httpCookieStore;
            NSLog(@"cookieStore *********************: %@",cookieStore);
            [cookieStore getAllCookies:^(NSArray* cookies) {
                NSHTTPCookie *cookie;
                for(cookie in cookies){
                   NSLog(@"%@",cookie)
                }
                self->updatedCookie = updatedCockies;
                NSLog(@"cookie *********************: %@", self->updatedCookie);
            }];
        }
    }
    

    Every time you want new cookie so you need to write below code: Given Sharpio

    Swift :

    let config = WKWebViewConfiguration()
    if #available(iOS 9.0, *) {
        config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()
    } else {
         // I have no idea what to do for iOS 8 yet but this works in 9.
    }
    
    let webView = WKWebView(frame: .zero, configuration: config)
    

    Objective C--

    WKWebViewConfiguration *wkWebConfig = [WKWebViewConfiguration new];
        wkWebConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
    
    
    self.webView = [[WKWebView alloc] initWithFrame: CGRectZero
                                          configuration: wkWebConfig];
    

    *******Every time you will get new cookies********

提交回复
热议问题