Webview with HTTP Basic-Auth

Hey,


how i can show my Webview and connect auto. with Basic-Auth?


Is this correct or how would you do it?



@IBOutlet weak var WebView: UIWebView!
override func viewDidLoad() {
   
super.viewDidLoad()
   
// Do any additional setup after loading the view, typically from a nib.
  

   
let username = "user"
   
let password = "pw"
   
let loginString = String(format: "%@:%@", username, password)
   
let loginData = loginString.data(using: String.Encoding.utf8)!
   
let base64LoginString = loginData.base64EncodedString()
  

   
// create the request
   
let url = URL(string: "http://myurl.com/")
   
var request = URLRequest(url: url!)


   
request.httpMethod = "POST"
   
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

   
let urlConnection = NSURLConnection(request: request, delegate: self)
   
WebView.loadRequest(request);
  

Replies

forgot writing this under the code...


The issue: When I start the App the first time it works.

But when i reload the website the authentication isn't saved, so just a white screen is shown.

I think I need a Session but I don't know how I can do that.

This is very tricky to do reliably with UIWebView. Fortunately it’s very easy to do with WKWebView (via the

webView(_:didReceive:completionHandler:)
delegate callback). You should make the switch to the modern web view API.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"