title: Autofill Username and Password WKWebview Swift 3 Xcode
body: <p>I am trying to make an app in Swift 3 using the WKWebView class to go to a website and autofill in the Username and password.  I have tried search for days and only find answers using Obj-C and old versions of swift.</p>
  
  <p>I tried using the solution proposed here <a href="https://stackoverflow.com/questions/26329771/autofill-username-and-password-uiwebview-swift">Autofill Username and Password UIWebView Swift</a></p>
  
  <p>However this did not work for me in Swift 3.  Here is my example code:</p>
  
  <pre><code>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 &amp;&amp; countElements(savedPassword!) != 0) {
          let loadUsernameJS = "var inputFields = document.querySelectorAll(\"input[name='username']\"); \\ for (var i = inputFields.length &gt;&gt;&gt; 0; i--;) { inputFields[i].value = \'\(savedUsername)\';}"
          let loadPasswordJS = "var inputFields = document.querySelectorAll(\"input[name='password']\"); \\ for (var i = inputFields.length &gt;&gt;&gt; 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.
  }
  
  
  
  }
  </code></pre>