单独的cookie存储为两个(UIWebView或WKWebView)

时间:2016-08-02 04:13:22

标签: ios swift uiwebview wkwebview nshttpcookie

我想在不同的webView中登录同一网站的多个帐户。例如,我有Tab Bar Controller,其中包含三个视图控制器,每个视图控制器包含webView。例如,我在每个班级中为stackoverflow嵌入了webView个网址。用户如何使用这三个webView同时登录到不同的帐户?我试过这个,但我一次只能登录一个用户。 我发现我需要为每个cookie创建单独的UIWebView,但大多数答案都在objective-c而不是我想要的正确答案。例如(First Second Third) 任何人都可以告诉我我该怎么办?

class FirstViewController: UIViewController , UIWebViewDelegate{

    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        webView.delegate = self
        let requestURL = NSURL(string: "http://stackoverflow.com")
        let request = NSURLRequest(URL: requestURL!)
        activityIndicator.hidesWhenStopped = true
        activityIndicator.startAnimating()
        webView.loadRequest(request)

    }
       func webViewDidFinishLoad(webView: UIWebView) {
        activityIndicator.stopAnimating()
    }

}

class SecondViewController: UIViewController, UIWebViewDelegate{

    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        webView.delegate = self
        let requestURL = NSURL(string: "http://stackoverflow.com")
        let request = NSURLRequest(URL: requestURL!)
        activityIndicator.hidesWhenStopped = true
        activityIndicator.startAnimating()
        webView.loadRequest(request)

    }
        func webViewDidFinishLoad(webView: UIWebView) {
        activityIndicator.stopAnimating()
    }


}

由于

The preview of my executing code.

1 个答案:

答案 0 :(得分:6)

您可以使用WKWebView的不同实例WKWebSiteDataStore执行此操作:

let configuration1 = WKWebViewConfiguration()
configuration1.websiteDataStore = WKWebsiteDataStore.nonPersistent()
self.webView1 = WKWebView(frame: CGRect.zero, configuration: configuration1)
self.view.addSubview(self.webView1)

let configuration2 = WKWebViewConfiguration()
configuration2.websiteDataStore = WKWebsiteDataStore.nonPersistent()
self.webView2 = WKWebView(frame: CGRect.zero, configuration: configuration2)

不幸的是,在重新启动应用后,您将丢失webView数据(例如Cookie,缓存等),因为非持久性WKWebsiteDataStore无法保存到磁盘(您可能会注意到WKWebsiteDataStore实现NSCoding,但它不适用于非持久性商店。)