Given a short URL https://itun.es/us/JB7h_, How do you expand it into the full URL?
Zelko
Extension
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()
}
}
Example
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
}
来源:https://stackoverflow.com/questions/34710519/expand-a-short-url-in-swift