Advertisement
thieumao

Handle Authentication in WebView with Swift 3

Mar 11th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.08 KB | None | 0 0
  1. import UIKit
  2.  
  3. class ViewController: UIViewController {
  4.  
  5.     @IBOutlet weak var webView: UIWebView!
  6.     let path = "http://42.119.128.237/"
  7.    
  8.     override func viewDidLoad() {
  9.         super.viewDidLoad()
  10.         let url = URL(string: path)
  11.         let request = URLRequest(url: url!);
  12.         webView.loadRequest(request);
  13.         NSURLConnection(request: request, delegate: self)
  14.     }
  15.  
  16. }
  17.  
  18. extension ViewController : NSURLConnectionDataDelegate {
  19.    
  20.     func connection(_ connection: NSURLConnection, didReceive challenge: URLAuthenticationChallenge) {
  21.         showAlert()
  22.     }
  23.    
  24.     func showAlert(){
  25.        
  26.         let alertController = UIAlertController(title: "Authentication Required", message: nil, preferredStyle: .alert)
  27.        
  28.         let saveAction = UIAlertAction(title: "Login", style: .default, handler: {
  29.             alert -> Void in
  30.            
  31.             let firstTextField = alertController.textFields![0] as UITextField
  32.             let secondTextField = alertController.textFields![1] as UITextField
  33.  
  34.             var urlComponents = URLComponents(string: self.path)
  35.             urlComponents?.user = firstTextField.text //"admin"
  36.             urlComponents?.password = secondTextField.text//"test"
  37.             let url = urlComponents?.url;
  38.             let request = URLRequest(url: url!);
  39.             self.webView.loadRequest(request);
  40.         })
  41.        
  42.         let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
  43.             (action : UIAlertAction!) -> Void in
  44.            
  45.         })
  46.        
  47.         alertController.addTextField { (textField : UITextField!) -> Void in
  48.             textField.placeholder = "Enter Username"
  49.         }
  50.         alertController.addTextField { (textField : UITextField!) -> Void in
  51.             textField.placeholder = "Enter Password"
  52.             textField.isSecureTextEntry = true
  53.         }
  54.        
  55.         alertController.addAction(saveAction)
  56.         alertController.addAction(cancelAction)
  57.        
  58.         self.present(alertController, animated: true, completion: nil)
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement