Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 22, 2018 04:37
Show Gist options
  • Save KentarouKanno/eaafce4c05d437b56e348741c9624c41 to your computer and use it in GitHub Desktop.
Save KentarouKanno/eaafce4c05d437b56e348741c9624c41 to your computer and use it in GitHub Desktop.
UIWebView+

UIWebView + extension

import UIKit

extension UIWebView {

    /// WebViewのローカルストレージに値を設定する
    ///
    /// - Parameter dict: 設定する辞書
    func setLocalStorage(dict: Dictionary<String, String>) {
        for item in dict {
            self.stringByEvaluatingJavaScript(from: "localStorage.setItem('\(item.key)', '\(item.value)')")
        }
    }
    
    /// WebViewのローカルストレージから値を取得する
    ///
    /// - Parameter keys: キーの配列
    /// - Returns: 取得できた辞書(値がないnil、空文字の場合は返却しない)
    func getLocalStorage(keys: [String]) -> Dictionary<String, String> {
        var dict: Dictionary<String, String> = [:]
        for key in keys {
            if let value = self.stringByEvaluatingJavaScript(from: "localStorage.getItem('\(key)')"),
                !value.isEmpty  {
                dict[key] = value
            }
        }
        return dict
    }
    
    /// WebViewのローカルストレージからキー名(配列)を指定して値を削除する
    ///
    /// - Parameter keys: キーの配列
    func removeLocalStorage(keys: [String]) {
        for key in keys {
            self.stringByEvaluatingJavaScript(from: "localStorage.removeItem('\(key)')")
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment