iOS - 临时会话和 UIWebView
iOS - Ephemeral Session and UIWebView
我想使用 URLSession
.
将网页加载到 UIWebView
临时会话,的确,因为我不想存储会话,例如,如果我在 Twitter/FB/whatever 网站上登录。
所以,我有一个名为 webPage
的 UIWebView
@IBOutlet var webPage: UIWebView!
a UITextField
,我可以在其中写 URL
@IBOutlet var urlField: UITextField!
在这个文本字段旁边,我有一个 UIButton
,它实现了这个操作
@IBAction func sendUrl(_ sender: Any) {
let stringUrl = urlField.text
let url = URL (string: stringUrl!)
openPageWithSession(url: url!)
}
和函数 openPageWithSession
,其中我使用 临时会话
func openPageWithSession(url: URL){
let request = URLRequest(url: url)
let ephemeralConfiguration = URLSessionConfiguration.ephemeral
let ephemeralSession = URLSession(configuration: ephemeralConfiguration)
let task = ephemeralSession.dataTask(with: request) { (data, response, error) in
if error == nil {
self.webPage.loadRequest(request)
} else {
print("ERROR: \(error)")
}
}
task.resume()
}
网页加载正常。但是,如果我在 Twitter 上登录,然后关闭应用程序,如果我重新打开应用程序并再次导航 Twitter,我已经登录了!
为什么?临时会话在被杀死后不会失效?
来自上面的评论。
而不是 self.webPage.loadRequest(request)
,您应该使用:
self.webView.load(data, mimeType: "text/html", textEncodingName: "", baseURL: url).
这样您就可以使用您创建的临时会话。否则你只是正常加载网络视图,根本没有短暂的会话。
我想使用 URLSession
.
UIWebView
临时会话,的确,因为我不想存储会话,例如,如果我在 Twitter/FB/whatever 网站上登录。
所以,我有一个名为 webPage
UIWebView
@IBOutlet var webPage: UIWebView!
a UITextField
,我可以在其中写 URL
@IBOutlet var urlField: UITextField!
在这个文本字段旁边,我有一个 UIButton
,它实现了这个操作
@IBAction func sendUrl(_ sender: Any) {
let stringUrl = urlField.text
let url = URL (string: stringUrl!)
openPageWithSession(url: url!)
}
和函数 openPageWithSession
,其中我使用 临时会话
func openPageWithSession(url: URL){
let request = URLRequest(url: url)
let ephemeralConfiguration = URLSessionConfiguration.ephemeral
let ephemeralSession = URLSession(configuration: ephemeralConfiguration)
let task = ephemeralSession.dataTask(with: request) { (data, response, error) in
if error == nil {
self.webPage.loadRequest(request)
} else {
print("ERROR: \(error)")
}
}
task.resume()
}
网页加载正常。但是,如果我在 Twitter 上登录,然后关闭应用程序,如果我重新打开应用程序并再次导航 Twitter,我已经登录了!
为什么?临时会话在被杀死后不会失效?
来自上面的评论。
而不是 self.webPage.loadRequest(request)
,您应该使用:
self.webView.load(data, mimeType: "text/html", textEncodingName: "", baseURL: url).
这样您就可以使用您创建的临时会话。否则你只是正常加载网络视图,根本没有短暂的会话。