투케이2K

203. (ios/swift) [간단 소스] WKWebview 웹뷰 로드 수행 시 사전 캐시, 쿠키, 세션, 웹뷰 인스턴스 초기화 정리 본문

IOS

203. (ios/swift) [간단 소스] WKWebview 웹뷰 로드 수행 시 사전 캐시, 쿠키, 세션, 웹뷰 인스턴스 초기화 정리

투케이2K 2022. 9. 20. 08:22
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT

 

[소스 코드]

    // MARK: - [웹뷰 다시 로드 수행 (전) 캐시 및 세션 초기화 부분]
    func clearWebViewInit(){
        print("")
        print("===============================")
        print("[A_Main >> clearWebViewInit() :: 웹뷰 인스턴스 초기화 실시]")
        print("===============================")
        print("")
        
        // -----------------------------------------

        if self.main_webview != nil { // [웹뷰 인스턴스가 null 이 아닌 경우]
            
            // -----------------------------------------
            
            // [저장된 쿠키 확인]
            if #available(iOS 11.0, *) {

                self.main_webview!.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in

                    if cookies.count>0 { // [저장된 쿠키가 있는 경우]

                        for cookie in cookies {
                            self.main_webview!.configuration.websiteDataStore.httpCookieStore.delete(cookie, completionHandler: {
                                print("")
                                print("===============================")
                                print("[A_Main >> clearWebViewInit() :: [웹뷰 인스턴스] 사전 쿠키 및 세션 데이터 삭제]")
                                print("설 명 :: ", "자바스크립트에 저장된 [개별] 쿠키값 제거 실시")
                                print("key :: \(cookie.name)")
                                print("value :: \(cookie.value)")
                                print("===============================")
                                print("")
                            })
                        }

                    }
                    else { // [저장된 쿠키가 없는 경우]
                        print("")
                        print("===============================")
                        print("[A_Main >> clearWebViewInit() :: [웹뷰 인스턴스] 사전 쿠키 및 세션 데이터 삭제]")
                        print("결 과 :: 저장된 쿠키 없음")
                        print("===============================")
                        print("")
                    }
                }

            }
            else {
                print("")
                print("===============================")
                print("[A_Main >> clearWebViewInit() :: [웹뷰 인스턴스] 사전 쿠키 및 세션 데이터 삭제]")
                print("error [에러] :: iOS 11.0 미만 디바이스")
                print("===============================")
                print("")
            }
            // -----------------------------------------
            
            // [웹뷰 인스턴스 제거 실시]
            self.main_webview?.removeFromSuperview()
            self.main_webview = nil

            // -----------------------------------------
            
            // [자바스크립트 통신 사용 초기화]
            self.javascriptController = WKUserContentController()
            self.javascriptConfig.websiteDataStore = WKWebsiteDataStore.default() // [디폴트]
            
            // -----------------------------------------
            // [원하는 캐시 데이터만 골라서 삭제]
            let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeCookies, // 웹 쿠키,

                                                 // WKWebsiteDataTypeDiskCache, // 디스크 캐시
                                                 // WKWebsiteDataTypeMemoryCache, // 메모리 캐시

                                                 // WKWebsiteDataTypeLocalStorage, // 로컬 스토리지
                                                 // WKWebsiteDataTypeSessionStorage, // 세션 스토리지

                                                 WKWebsiteDataTypeOfflineWebApplicationCache, // 앱 캐시
                                                 WKWebsiteDataTypeWebSQLDatabases, // 웹 SQL 데이터 베이스
                                                 WKWebsiteDataTypeIndexedDBDatabases // 데이터 베이스 정보
                                                ])

            let date = NSDate(timeIntervalSince1970: 0)

            WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{
                print("")
                print("===============================")
                print("[A_Main >> clearWebViewInit() :: [웹뷰 인스턴스] WKWebsiteDataStore 사전 쿠키 및 세션 데이터 삭제]")
                print("===============================")
                print("")
            })
            
            // -----------------------------------------
            
            // [설치된 날짜 가져오는 코드]
            let urlToDocumentsFolder: URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
            let installDate = try? FileManager.default.attributesOfItem(atPath: (urlToDocumentsFolder?.path)!)[.creationDate] as! Date
            
            // [설치된 날짜부터 지금까지의 cookie all clear]
            URLSession.shared.configuration.httpCookieStorage?.removeCookies(since: installDate!)
            
            // -----------------------------------------
            
            // [URL 요청 후 잔여 캐시 데이터 삭제]
            URLCache.shared.removeAllCachedResponses()
            
            // -----------------------------------------
            
            // [뷰 컨트롤러 자식들 모두 없애기]
            self.view.removeFromSuperview()
            
            // -----------------------------------------
            
        }
        else { // [웹뷰 인스턴스가 null 인 경우]
            print("")
            print("===============================")
            print("[A_Main >> clearWebViewInit :: [웹뷰 인스턴스] [웹뷰 화면 초기화] main_webview 웹뷰 객체 널 (NULL) 임]")
            print("[로직 :: WKWebsiteDataStore 쿠키, 세션 객체 초기화 실시]")
            print("===============================")
            print("")

            // -----------------------------------------
            
            // [자바스크립트 통신 사용 초기화]
            self.javascriptController = WKUserContentController()
            self.javascriptConfig.websiteDataStore = WKWebsiteDataStore.default() // [디폴트]
            
            // -----------------------------------------
            // [원하는 캐시 데이터만 골라서 삭제]
            let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeCookies, // 웹 쿠키,

                                                 // WKWebsiteDataTypeDiskCache, // 디스크 캐시
                                                 // WKWebsiteDataTypeMemoryCache, // 메모리 캐시

                                                 // WKWebsiteDataTypeLocalStorage, // 로컬 스토리지
                                                 // WKWebsiteDataTypeSessionStorage, // 세션 스토리지

                                                 WKWebsiteDataTypeOfflineWebApplicationCache, // 앱 캐시
                                                 WKWebsiteDataTypeWebSQLDatabases, // 웹 SQL 데이터 베이스
                                                 WKWebsiteDataTypeIndexedDBDatabases // 데이터 베이스 정보
                                                ])

            let date = NSDate(timeIntervalSince1970: 0)

            WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{
                print("")
                print("===============================")
                print("[A_Main >> clearWebViewInit() :: [웹뷰 인스턴스] WKWebsiteDataStore 사전 쿠키 및 세션 데이터 삭제 [2]]")
                print("===============================")
                print("")
            })
            
            // -----------------------------------------
            
            // [설치된 날짜 가져오는 코드]
            let urlToDocumentsFolder: URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
            let installDate = try? FileManager.default.attributesOfItem(atPath: (urlToDocumentsFolder?.path)!)[.creationDate] as! Date
            
            // [설치된 날짜부터 지금까지의 cookie all clear]
            URLSession.shared.configuration.httpCookieStorage?.removeCookies(since: installDate!)
            
            // -----------------------------------------
            
            // [URL 요청 후 잔여 캐시 데이터 삭제]
            URLCache.shared.removeAllCachedResponses()
            
            // -----------------------------------------

        }
        // -----------------------------------------
    }

 

반응형
Comments