用户登录后,返回应用程序(WebKit、swift、json)



一旦用户通过身份验证,我将尝试关闭WebKit浏览器。我建立了一个后端rails API,我的swift前端正在向其发出请求。我的rails API通过关于用户的凭据进行响应。

struct LoginView: UIViewRepresentable {
let request: URLRequest
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}

func webViewDidFinishLoad(_ uiView: LoginView) {
if let text = uiView.request.url?.absoluteString{
print("THIS IS THE URL (text)")
}
}
}

我的API返回带有凭证密钥的JSON(包含令牌(,如果响应中有凭证密钥,我想返回到我的应用程序,因为用户将登录。

您可以使用以下WKWebView的委托方法来获取回调&移回应用程序。

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping ((WKNavigationActionPolicy) -> Void)) {
if let url = navigationAction.request.url {
print(url.absoluteString)
if url.absoluteString.hasPrefix("your_url"){
// Authenticated, remove webview and back to app
self.stopLoading()
}
}
decisionHandler(.allow)
}
func stopLoading() {
webView.removeFromSuperview()
//Move to view controller
// Load & push/present your view controller here
}

如果它能解决你的问题,请告诉我。很乐意提供更多帮助。

最新更新