Pey*_*tle 5 cookies uiwebview ios react-native
我的 WebView 应显示具有 cookie 身份验证的网页。该页面需要在登录时获取会话 ID cookie。为了进行身份验证,我使用 fetch() 将登录请求发送到网站。
登录成功后,我可以看到收到了正确的 cookie。成功后,我将启动 WebView。
它在 Android 上完美运行,但在 iOS 上却无法运行。
昨天我尝试了很多关于 SO 建议的不同方法,比如使用 react-native-cookies 手动获取 cookie,但没有任何帮助。
下面是一个与我的应用程序执行相同操作的示例组件。我认为问题可能出在我的应用程序的配置中,所以我创建了这个非常简单的示例,它也有同样的问题。
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
response: null,
}
}
async componentDidMount() {
const response = await this.logIn()
console.log('LogIn completed', response)
this.setState({
response: response
})
}
async logIn() {
const url = 'myurl/login?email=email&password=password'
const headers = {'MyHeader': 'Header text'}
try {
let response = await fetch(url, {
method: 'POST',
headers: headers,
// credentials: 'same-origin',
credentials: 'include',
})
return Promise.resolve(response)
} catch (error) {
return Promise.reject(error)
}
}
render() {
const url = 'myurl/dashboard'
const headers = {'MyHeader': 'Header text'}
return (
<WebView source = {{
uri: url,
headers: headers
}}
/>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我在 iOS 9 和 iOS 11 模拟器以及 iOS 11 设备上对其进行了测试。
总结一下这个问题:为什么我通过 fetch 获得的 cookie 不会只传递给 iOS 上的 WebView。
我已经找到问题了。缺少 cookie 只是由于错误的“User-Agent”标头导致的错误授权的结果。我试图在 WebView 标头中传递用户代理。它在 Android 上运行良好,但在 iOS 上需要解决方法。要在 iOS 上设置 User-Agent 标头,您需要从 AppDelegate 更改 UserDefaults。
NSString *userAgent = @"YourUserAgentString";
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
Run Code Online (Sandbox Code Playgroud)
感谢这个答案:/sf/answers/2654255271/
| 归档时间: |
|
| 查看次数: |
6561 次 |
| 最近记录: |