Pingu
Pingu

Reputation: 101

Swift: How to put current URL from UIWebView into UITextField?

(XCode 6.3.2, Swift 1.2) I simply want to put the URL of the loaded webpage of the UIWebView into an UITextField. The solutions which I found here doesn't work for me.

Here's my code:

@IBOutlet weak var addressBar: UITextField!
@IBOutlet weak var webView: UIWebView!

//some more code...

func webViewDidFinishLoad(webView : UIWebView) {
   self.addressBar.text = (self.webView.request?.URL.absoluteString)!
}

Swift Compiler Error: Value of optional type 'NSURL?' not unwrapped; did you mean to use '!' or '?'?

Any ideas or hints would be very appreciated. Thanks.

EDIT:
The answer from Airspeed Velocity works for me (see working code below). However I recognized that sometimes the loaded URL isn't correctly written back to the UITextField.
It's reproducible for example on Vimeo. When I click on a video link on vimeo.com the URL should change to something like: https://vimeo.com/105060039
On mobile Safari this works fine but not on the UIWebView. To the URL "https://vimeo.com/" the video number isn't added.
What I'm doing wrong? Is there an other possibility to get the current URL?

@IBOutlet weak var addressBar: UITextField!
@IBOutlet weak var webView: UIWebView!

//some more code...

func webViewDidFinishLoad(webView: UIWebView) {
   addressBar.text = webView.request?.URL?.absoluteString
}

Upvotes: 2

Views: 3328

Answers (2)

Gerard G
Gerard G

Reputation: 3463

Swift 3.2

self.addressBar.text = self.webView.request?.url?.absoluteString

Upvotes: 0

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

webView.request is optional, so you’re using optional chaining. You just need to do the same with the request’s URL, which is also optional:

self.addressBar.text = self.webView.request?.URL?.absoluteString

Note, there’s no need to force-unwrap this with the ! on the end. This is because self.addressBar.text is itself of type String?.

Upvotes: 2

Related Questions