简体   繁体   English

如何使用现有的不记名令牌初始化 WKWebView

[英]How to init WKWebView with already existing bearer token

I'm implementing an iOS app which authenticates to my web service and receives a token.我正在实现一个 iOS 应用程序,它对我的​​ Web 服务进行身份验证并接收一个令牌。 I have embedded a WKWebView to my app so that I can open one specific web page in which I have javascript that tries to read the token from local storage.我已将WKWebView嵌入到我的应用程序中,以便我可以打开一个特定的网页,其中有 javascript 尝试从本地存储读取令牌。 How can I init the WKWebView so that my token is accessible from the local storage?如何初始化WKWebView以便可以从本地存储访问我的令牌?

Edit: Here is a discussion telling a way to enable local storage: iOS WKWebView does not support local storage but it seems that adding an item to local storage from app code is not possible.编辑:这是一个讨论启用本地存储的方法: iOS WKWebView 不支持本地存储,但似乎无法从应用程序代码将项目添加到本地存储。

Try setting the token in header of request that would pe passed to webview, as:尝试在将 pe 传递给 webview 的请求标头中设置令牌,如下所示:

if let url = URL(string: "https://yourdomain.com") {
    var request = URLRequest(url: url)
    request.addValue("auth token value", forHTTPHeaderField: "Authorization")
}

you can add to local storage: key is AccessToken and value is the token您可以添加到本地存储:key 是 AccessToken,value 是令牌

webView.configuration.userContentController.addUserScript(script())

func script() -> WKUserScript {

 let source = "localStorage.setItem('AccessToken', '\(getAccessToken())');"

 return WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
}


I have created a viewcontroller which will create webview instance for you.我创建了一个视图控制器,它将为您创建 webview 实例。

class ViewController: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!

        //Kind of crazy stuff
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //General view with page, followed by link
        let url = URL(string: "https://google.com")! //example
        webView.load(URLRequest(url: url))

    }
        //I do not sure, is that ui?
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM