Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Given a short URL https://itun.es/us/JB7h_, How do you expand it into the full URL?
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Given a short URL https://itun.es/us/JB7h_, How do you expand it into the full URL?
extension NSURL {
func expandURLWithCompletionHandler(completionHandler: (NSURL?) -> Void) {
let dataTask = NSURLSession.sharedSession().dataTaskWithURL(self, completionHandler: {
_, response, _ in
if let expandedURL = response?.URL {
completionHandler(expandedURL)
}
})
dataTask.resume()
}
}
let shortURL = NSURL(string: "https://itun.es/us/JB7h_")
shortURL?.expandURLWithCompletionHandler({
expandedURL in
print("ExpandedURL:\(expandedURL)")
//https://itunes.apple.com/us/album/blackstar/id1059043043
})
The final resolved URL will be returned to you in the NSURLResponse: response.URL
.
You should also make sure to use the HTTP HEAD
method to avoid downloading unnecessary data (since you don't care about the resource body).
extension NSURL
{
func resolveWithCompletionHandler(completion: NSURL -> Void)
{
let originalURL = self
let req = NSMutableURLRequest(URL: originalURL)
req.HTTPMethod = "HEAD"
NSURLSession.sharedSession().dataTaskWithRequest(req) { body, response, error in
completion(response?.URL ?? originalURL)
}.resume()
}
}
// Example:
NSURL(string: "https://itun.es/us/JB7h_")!.resolveWithCompletionHandler {
print("resolved to \($0)") // prints https://itunes.apple.com/us/album/blackstar/id1059043043
}