1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WKWebViewのWKWebsiteDataStoreを削除する方法

Last updated at Posted at 2023-11-06

要件

WKWebViewのLocalStorageに設定している値をアプリ起動時やアカウント切り替え時などにネイティブ側で削除したい。

Data Store Record Types

削除方法

参考:WebCacheCleaner.swift
https://gist.github.com/insidegui/4a5de215a920885e0f36294d51263a15

WebViewModel.swift
/// WebViewのDataStoreの値を初期化する
private func cleanWKWebsiteDataRecord() {
    // Cookieデータを削除
    HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
    
    // WKWebsiteDataStoreからWebサイトデータを取得
    WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
        records.forEach { record in
            // 特定のデータレコードを削除
            WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
        }
    }
}

確認方法

WebViewModel.swift
/// ローカルストレージの値をデバッグ出力する
private func printLocalStorageValue() {
    webView.evaluateJavaScript("localStorage.getItem('hoge-key')") { result, error in
        if let error = error {
            print(error)
            return
        }
        print("hoge-keyの値: \(result ?? "nil")")
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?