iOS之webView与JS交互篇

31期_iOS_WKWebView的cookie处理

2023-09-02  本文已影响0人  萧修

WK的cookie的应用

NSDictionary *properties = @{
                                   NSHTTPCookieName : @"name",
                                   NSHTTPCookieValue : @"zhangsan",
                                   NSHTTPCookieDomain : @"域名",
                                   NSHTTPCookiePath : @"/",
                                   NSHTTPCookieExpires:[NSDate dateWithTimeIntervalSinceNow:3600],
                                   NSHTTPCookieSecure : @(YES)
                                   };
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
[NSHTTPCookieStorage.sharedHTTPCookieStorage setCookie:cookie];

[NSHTTPCookieStorage.sharedHTTPCookieStorage deleteCookie:cookie];//删除okie

WK设置cookie

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:@{};

WKWebsiteDataStore *websiteDataStore = config.websiteDataStore;
WKHTTPCookieStore *httpCookieStore = websiteDataStore.httpCookieStore;
[httpCookieStore setCookie:nil completionHandler:^{
                    
}];

仅支持iOS11之后


WK_EXTERN API_AVAILABLE(macos(10.13), ios(11.0))
@interface WKHTTPCookieStore : NSObject

- (instancetype)init NS_UNAVAILABLE;

/*! @abstract Fetches all stored cookies.
 @param completionHandler A block to invoke with the fetched cookies.
 */
- (void)getAllCookies:(void (^)(NSArray<NSHTTPCookie *> *))completionHandler;

/*! @abstract Set a cookie.
 @param cookie The cookie to set.
 @param completionHandler A block to invoke once the cookie has been stored.
 */
- (void)setCookie:(NSHTTPCookie *)cookie completionHandler:(nullable void (^)(void))completionHandler;

/*! @abstract Delete the specified cookie.
 @param completionHandler A block to invoke once the cookie has been deleted.
 */
- (void)deleteCookie:(NSHTTPCookie *)cookie completionHandler:(nullable void (^)(void))completionHandler WK_SWIFT_ASYNC_NAME(deleteCookie(_:));

/*! @abstract Adds a WKHTTPCookieStoreObserver object with the cookie store.
 @param observer The observer object to add.
 @discussion The observer is not retained by the receiver. It is your responsibility
 to unregister the observer before it becomes invalid.
 */
- (void)addObserver:(id<WKHTTPCookieStoreObserver>)observer;

/*! @abstract Removes a WKHTTPCookieStoreObserver object from the cookie store.
 @param observer The observer to remove.
 */
- (void)removeObserver:(id<WKHTTPCookieStoreObserver>)observer;

@end

案例

H5需要用到登录信息,原生需要将此传递给h5,我们通过js bridge方法传递。

从wk代理方法中decidePolicyForNavigationAction请求开始之前处理cookie,没有则添加,添加通过usercontentviewcontroller或者wkusersript添加。

- (void)setCookieWithUrl:(NSURL *)url {
    NSString *host = [url host];
    if ([self.cookieURLs containsObject:host]) {
        return;
    }
    [self.cookieURLs addObject:host];
    
    WKUserScript *wkcookieScript = [[WKUserScript alloc] initWithSource:self.webviewCookie
                                                          injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                       forMainFrameOnly:NO];
    [self.cookieWebview.configuration.userContentController addUserScript:wkcookieScript];
    
    NSString *baseWebUrl = [NSString stringWithFormat:@"%@://%@", url.scheme, url.host];
    [self.cookieWebview loadHTMLString:@"" baseURL:[NSURL URLWithString:baseWebUrl]];
}
- (void)removeWKWebviewCookie {
    self.webviewCookie = nil;
    [self.cookieWebview.configuration.userContentController removeAllUserScripts];
    
    NSMutableArray<NSHTTPCookie *> *cookies = [NSMutableArray array];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([self.cookieData.allKeys containsObject:cookie.name]) {
            [cookies addObjectOrNil:cookie];
        }
    }];
    
    [cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull cookie, NSUInteger idx, BOOL * _Nonnull stop) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }];
}
上一篇下一篇

猜你喜欢

热点阅读