问题
I have a Ruby on Rails backend web application. I use iOS application as a web client (WKWebView) written in swift. The authentication token is stored as a session cookies variable on the backend:
session['token'] = generate_token
The problem is that accidentally this session variable is lost and the flow is redirected to login page. The WKWebView is not closed, just used to process HTTP requests. I'm not able to figure out, why this accidentally happens.
回答1:
Since you are using just a webView and not default Safari browser meaning you are making your custom browser hence you are responsible to handle things like caching your token for the current session. My suggestion, if you want the token to be stored and used only once then create a variable something like
let accessToken = "your json web token"
Then pass it as a header when making a request to your server.
If you want to maintain access then you might want to save your token in keyChain or userDefaults depending on the level of security.
Navigation and other user interactions
As I mentioned, using wkwebView meaning you are making your own browser so you have to detect subsequent requests as the user interact with your web pages. For navigation, you have to use WKNavigationDelegate methods.
If WKNavigationDelegate does not solve your problem then you have to make use of Javascript events ie.. post an event when user visit a certain page and use WKScriptMessageHandler to respond to those events by passing the acess token etc..
来源:https://stackoverflow.com/questions/57974186/wkwebview-sometimes-loses-the-session-variable