Get current URL of UIWebView
Matt's version is much cleaner. I recommend everyone to use that one instead of this
You could try this:
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location"];
How can I get the URL from webView in swift
You are not getting url because webView
has not finished the loading of that requested URL
, you can get that URL
in webViewDidFinishLoad
method of UIWebviewDelegate
. For that you need to set delegate of webView
with your current ViewController
and need to implement UIWebviewDelegate
.
webView.delegate = self
Now you can get current loaded URL
of webView
in webViewDidFinishLoad
method.
func webViewDidFinishLoad(_ webView: UIWebView) {
if let text = webView.request?.url?.absoluteString{
print(text)
}
}
iOS Swift : can't Retrieve current url loaded in UIwebView
There are couple of UIWebViewDelegate
such as shouldStartLoadWithRequest
or webViewDidStartLoad
or webViewDidFinishLoad
or didFailLoadWithError
that help you to accomplish your goal. If you want to perform operation after view did finished then implement this delegate method
Swift 3
if let currentURL = webView.request?.url?.absoluteString{
print(currentURL)
}
as it mentioned here.
Get Current URL (UIWebView)
NSString *currentURL = myWebView.request.URL.absoluteString;
UIWebView get current URL of SPA (single page application) website
Step 1: Creating a custom URLProtocol to catch data requests
class CustomURLProtocol: URLProtocol, URLSessionDataDelegate, URLSessionTaskDelegate {
// If this returns false, the first request will basically stops at where it begins.
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
print(self.request.url) // URL of Data requests made by UIWebView before loading.
URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil).dataTask(with: self.request).resume()
}
override func stopLoading() {
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
// Data request responses received.
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
// Data request data received.
self.client?.urlProtocol(self, didLoad: data)
self.urlSession(session, task: dataTask, didCompleteWithError: nil)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
self.client?.urlProtocol(self, didFailWithError: error)
return
}
print(self.request.url) // URL of Data requests completed.
self.client?.urlProtocolDidFinishLoading(self)
}
}
Step 2: Registering your custom URLProtocol
Register your custom URLProtocol before loading your SPA in UIWebview.
URLProtocol.registerClass(CustomURLProtocol.self)
Hope this helps! Sorry for the delay, was caught up at work.
How to get http:// address of page loaded in UIWebView?
Please make your class the delegate of the webview using
webView.delegate = self
Then override the delegate method,
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("current url is \(request.mainDocumentURL!.absoluteString)")
return true;
}
This will give the current url going to be loaded
How to get the url of currently playing video in UIWebview
There is a hacky way of doing it by listening for the AVPlayerItemBecameCurrentNotification
notification. This notification is fired when a UIWebView shows the media player, and it sends an AVPlayerItem
as the notification's object.
For example:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemBecameCurrent:)
name:@"AVPlayerItemBecameCurrentNotification"
object:nil];
-(void)playerItemBecameCurrent:(NSNotification*)notification {
AVPlayerItem *playerItem = [notification object];
if(playerItem == nil) return;
// Break down the AVPlayerItem to get to the path
AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
NSURL *url = [asset URL];
NSString *path = [url absoluteString];
}
This works for any video (and audio). However, I noticed you mentioned YouTube - it's worth pointing out Apple WILL reject your app if it has the ability to download YouTube videos AT ALL, because it's against YouTube's Terms of Service.
SWIFT: Why I can't get the current URL loaded in UIWebView?
If you put parentheses around this, the error goes away:
let currentURL : NSString = (webView.request?.URL.absoluteString)!
Related Topics
Test Whether a Uiview Is in the Middle of Animation
What Is Kcferrordomaincfnetwork Code=303
How to Check If a File Exists in Documents Folder
Usage of Protocols as Array Types and Function Parameters in Swift
Uiviewcontentmodescaleaspectfill Not Clipping
Kvo and Arc How to Removeobserver
Is a Date in Same Week, Month, Year of Another Date in Swift
(Swift) Storing and Retrieving Array to Nsuserdefaults
Why Is Uitextfield.Text an Optional
Using JSONencoder to Encode a Variable with Codable as Type
Detect iOS Application About to Delete
Cannot Use Instance Member Within Property Initializer
Nsdata Won't Accept Valid Base64 Encoded String
How to Show Alertview with Activity Indicator
Cannot Subscript a Value of Type '[Nsobject:Anyobject]' with an Index of Type 'String'
Swiftui - iOS 13 Uiviewrepresentable of Wkwebview Gets Thread 1: Exc_Breakpoint Crash
In Swift, How to Let Other Apps Continue to Play Audio When My App Is Open