我正在尝试使用应用程序登录网站。该项目有两个视图控制器,一个带有我创建的登录UI,另一个带有WKWebView。基本上,我想采用用户输入的参数并将其发送到WKWebView,然后登录并返回要在另一个视图控制器上呈现的数据。
注意:我已经尝试寻找一种API,但是该网站没有一个可访问的
这是我当前的操作方式,但是我遇到了无法解救返回的Nill错误的问题。
带有WebView的View Controller
<script>
var ports_dic = [16, 17, 18, 19, 20];
function loop_ports(){
var n_list = document.value = ports_dic["1/1/12"]
for (var i = 0; i < n_list.length; i++){
var span = document.createElement("SPAN");
span_element = console.log(ports_dict[i]);
span.appendChild(span_element);
document.getElementById("onu_tags").appendChild(span);
};
}
</script>
<body>
<div id="onu_tags" class="tags">
</div>
</body>
登录UI View Controller
import UIKit
import WebKit
class Web_View: UIViewController, WKUIDelegate {
var webView: WKWebView!
var viewControllerManager : ViewController!
override func viewDidLoad() {
super.viewDidLoad()
let HAC_URL = URL(string:"https://hac.friscoisd.org/HomeAccess/Account/LogOn?ReturnUrl=%2fhomeaccess%2f")
let request = URLRequest(url: HAC_URL!)
webView.load(request)
}
//loadsBackgroundView
override func loadView() {
let webConfig = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfig)
webView.uiDelegate = self
view = webView
}
//Username manager
func webViewDidFinishLoadUsername() {
webView.evaluateJavaScript("document.getElementByTagName(\"input\")[2].value = \(viewControllerManager.username)") {(result, error) in
if error != nil
{
print(result!)
}
else
{
print(error!)
}
}
}
//Password manager
func webViewDidFinishLoadPassword() {
webView.evaluateJavaScript("document.getElementByTagName(\"input\")[1].value = \(viewControllerManager.password)") {(result, error) in
if error != nil
{
print(result!)
}
else
{
print(error!)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
如果有更好的方法,请告知我
修改 这是我认为需要修复的行
var webView:WKWebView!
var viewControllerManager:ViewController!
此行弹出错误 webView.evaluateJavaScript(“ document.getElementByTagName(\” input \“)[2] .value =(viewControllerManager.username)”){(结果,错误)in
我有预感,这是因为我再次用力包裹了
答案 0 :(得分:0)
例如,您应该避免这样的强制展开:
用户名= usernameTextField.text!
if let usernameText = usernameTextField.text {
username = usernameText
}
由于我还不能添加评论,因此我认为您唯一的问题是“ 强制展开返回的Nill错误 ”。以上是我为避免这种情况的建议。
答案 1 :(得分:0)
隐藏webView
webView.isHidden = true
webView.isHidden = false