在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 }
- 在xcode中以MM / dd / yyyy格式转换date?
- iOS-如何在iOS 10中集成推送通知?
- 增加一个CKRecordvariables中的字段值,而不需要读取?
- becomeFirstResponder在iOS 8中不起作用
- 为什么self.view.subviews在viewDidLoad中是一个空的数组?
- 如何访问在XCUIApplication中设置的launchEnvironment和launchArguments,在XCode中运行UItesting?
- CoreBluetooth:无法findiPad
- 分类的UITableView与背景不显示静态单元格
- iOS – 自动发送电子邮件(不是来自用户的帐户)