2
我想在Swift 3中使用WKWebView類去一個網站並在用戶名和密碼中進行自動填充。我已經嘗試過搜索幾天,只能使用Obj-C和舊版本的swift找到答案。自動填充用戶名和密碼WKWebview Swift 3 Xcode
我試着用這裏提出Autofill Username and Password UIWebView Swift
解決方案然而,這並沒有斯威夫特3.工作對我來說這是我的示例代碼:
import Foundation
import UIKit
import WebKit
class spot: UIViewController, UIWebViewDelegate {
@IBOutlet weak var container: UIView!
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
webView = WKWebView()
container.addSubview(webView)
}
override func viewDidAppear(_ animated: Bool) {
let frame = CGRect(x:0, y:0, width:container.bounds.width, height:container.bounds.height)
webView.frame = frame
// Insert URL below to change launched page
let urlStr = "https://login.salesforce.com/"
let url = NSURL(string: urlStr)!
let request = NSURLRequest(url: url as URL)
webView.load(request as URLRequest)
}
func webViewDidFinishLoad(_ webView: UIWebView!) {
let savedUsername = UserDefaults.standard.string(forKey: "USERNAME")
let savedPassword = UserDefaults.standard.string(forKey: "PASSWORD")
if savedUsername == nil || savedPassword == nil {return}
if (countElements(savedUsername!) != 0 && countElements(savedPassword!) != 0) {
let loadUsernameJS = "var inputFields = document.querySelectorAll(\"input[name='username']\"); \\ for (var i = inputFields.length >>> 0; i--;) { inputFields[i].value = \'\(savedUsername)\';}"
let loadPasswordJS = "var inputFields = document.querySelectorAll(\"input[name='password']\"); \\ for (var i = inputFields.length >>> 0; i--;) { inputFields[i].value = \'\(savedPassword)\';}"
self.webView.stringByEvaluatingJavaScriptFromString(loadUsernameJS)
self.webView.stringByEvaluatingJavaScriptFromString(loadPasswordJS)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
親愛的上帝沒有。不要把密碼放在查詢中! –
此外,您應該使用KeyChain而不是UserDefaults來安全地存儲密碼。 –