如果网址较短https://itun.es/us/JB7h_,您如何将其扩展为完整的网址?
答案 0 :(得分:6)
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
})
答案 1 :(得分:5)
最终解析的网址将在NSURLResponse中返回给您:response.URL
。
您还应确保使用HTTP HEAD
方法以避免下载不必要的数据(因为您不关心资源主体)。
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
}