iOS

[iOS] WKWebView setCookie not working!!! 해결

i-moo 2019. 8. 8. 19:55
반응형

 

iOS Target을 11.0으로 올린 뒤 UIWebView에서 WKWebView 변환 작업을 했다.

동로그인일 경우, setCookie를 해주어야하는데... 생각했던 방법으로 정상적으로 작동을 안했다.

 

일단, WKWebView를 여러개를 사용하기때문에 WKWebViewConfiguration는 AppDelegate에서 초기화를 해주고 동일한 configuration을 사용하였다.

 

AppDelegate.m  (didFinishLaunchingWithOptions 메소드)

    self.wkWebViewConfiguration = [[WKWebViewConfiguration alloc] init];

    WKUserContentController *wkUserContentController = [[WKUserContentController alloc] init];
    WKProcessPool *wkProcessPool = [[WKProcessPool alloc] init];
    WKPreferences *wkPreferences = [[WKPreferences alloc] init];
    wkPreferences.javaScriptEnabled = YES;
    wkPreferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    self.wkWebViewConfiguration.userContentController = wkUserContentController;
    self.wkWebViewConfiguration.processPool = wkProcessPool;
    self.wkWebViewConfiguration.preferences = wkPreferences;

 

초기화한 configuration은 self.appDelegate.wkWebViewConfiguration 꺼내 사용했다.

(참고로, 여러개의 WKWebView에서 쿠키값을 공유하려면 같은 WKProcessPool을 사용해야한다.)

 

1. setCookie

[self.webView.configuration.websiteDataStore.httpCookieStore setCookie:cookie];

 

2. evaluateJavaScript

[self.webView evaluateJavaScript:[NSString stringWithFormat:@"document.cookie='%@=%@';domain='%@';path='%@';document.cookie='%@=%@';domain='%@';path='%@';", cookie.name, cookie.value, cookie.domain, cookie.path, cookie2.name, cookie2.value, cookie2.domain, cookie2.path] completionHandler:nil];

 

3. WKUserScript : A WKUserScript object represents a script that can be injected into a webpage.

(https://developer.apple.com/documentation/webkit/wkuserscript)

WKUserScript * cookieScript = [[WKUserScript alloc]
                                           initWithSource: [NSString stringWithFormat:@"document.cookie='%@=%@';domain='%@';path='%@';document.cookie='%@=%@';domain='%@';path='%@';", cookie.name, cookie.value, cookie.domain, cookie.path, cookie2.name, cookie2.value, cookie2.domain, cookie2.path] 
                                           injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

[self.appDelegate.wkWebViewConfiguration.userContentController addUserScript:cookieScript];

self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)  configuration:self.appDelegate.wkWebViewConfiguration];

[self.webView evaluateJavaScript:[NSString stringWithFormat:@"document.cookie='%@=%@';domain='%@';path='%@';document.cookie='%@=%@';domain='%@';path='%@';", cookie.name, cookie.value, cookie.domain, cookie.path, cookie2.name, cookie2.value, cookie2.domain, cookie2.path] completionHandler:nil];

 

3가지 모두 정상적으로 작동을 안하였다.

(3번 WKUserScript은 쿠키값은 적용되나 로그아웃했을 경우 계속 해당 쿠키를 가지고 있어 로그인이 작동하였다.)

 

4. WKWebsiteDataStore.nonPersistentDataStore (작동 O)

                                                                                 : Returns a new nonpersistent data store.

(https://developer.apple.com/documentation/webkit/wkwebsitedatastore/1532934-nonpersistentdatastore?language=occ)

 

            NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                                        @"domain", NSHTTPCookieDomain,
                                        @"/", NSHTTPCookiePath,
                                        @"name", NSHTTPCookieName,
                                        @"value", NSHTTPCookieValue, nil];
            
            NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
            
            NSDictionary *properties2 = [NSDictionary dictionaryWithObjectsAndKeys:
                                         @"domain", NSHTTPCookieDomain,
                                         @"/", NSHTTPCookiePath,
                                         @"name2", NSHTTPCookieName,
                                         @"value2", NSHTTPCookieValue, nil];
            
            NSHTTPCookie *cookie2 = [NSHTTPCookie cookieWithProperties:properties2];
            
            WKWebsiteDataStore *wkWebsiteDataStore = WKWebsiteDataStore.nonPersistentDataStore;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [wkWebsiteDataStore.httpCookieStore setCookie:cookie completionHandler:^{
                    [wkWebsiteDataStore.httpCookieStore setCookie:cookie2 completionHandler:^{
                        self.appDelegate.wkWebViewConfiguration.websiteDataStore = wkWebsiteDataStore;
                        
                        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)  configuration:self.appDelegate.wkWebViewConfiguration];

                        self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
                        
                        [self.webView setBackgroundColor:UIColor.whiteColor];
                        [self.webView setOpaque:NO];
                        
                        self.webView.UIDelegate = self;
                        self.webView.navigationDelegate = self;
                        
                        [self.view addSubview:self.webView];
                        
                        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL: [NSURL URLWithString:@"url"]]];
                    }];
                }];
            });

 

 

 

참고 url : 

https://developer.apple.com/documentation/webkit/wkwebview

 

WKWebView - WebKit | Apple Developer Documentation

The methods of the WKNavigationDelegate protocol help you implement custom behaviors that are triggered during a web view's process of accepting, loading, and completing a navigation request.

developer.apple.com

https://developer.apple.com/documentation/webkit?language=objc

 

WebKit | Apple Developer Documentation

WebKit provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited. WebKit greatly simplifies

developer.apple.com

https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882007-setcookie 

 

setCookie(_:completionHandler:) - WKHTTPCookieStore | Apple Developer Documentation

Instance Method setCookie(_:completionHandler:) Declarationfunc setCookie(_ cookie: HTTPCookie, completionHandler: (() -> Void)? = nil) ParameterscookiecompletionHandlerA block to invoke once the cookie has been set.

developer.apple.com

https://stackoverflow.com/questions/50974353/wkwebview-setting-cookie-not-possible-ios-11

 

WKWebView setting Cookie not possible (iOS 11+)

I am desperately trying to add a custom cookie to a WKWebView instance (without using Javascript or similar workarounds). From iOS 11 and upwards, Apple provides an API to do this: The WKWebViews

stackoverflow.com

 

 

반응형