How can I get the final redirected online url? I was thinking about using an URLSession data or download task.
URLSession
has two ways to deal with this:
-
The
urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)
delegate method gives you control over the redirection process. -
If you only need the final URL, check out the
currentRequest
property (versus theoriginalRequest
property).
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
2 Likes
Thanks. I'm now using the response
of a data task:
func redirectedURL(for url: URL, completionHandler: @escaping (URL?, Error?) -> Void) {
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request, completionHandler: { _, response, error in
if let httpResponse = response as? HTTPURLResponse, let location = httpResponse.allHeaderFields["Location"] as? String, let locationURL = URL(string: location) {
completionHandler(locationURL, error)
}
})
}