在Swift中展开一个简短的URL

给定一个简短的URL https://itun.es/us/JB7h_ ,如何将其扩展为完整的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 }) 

最终解析的URL将在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 }