Expand a short URL in Swift [closed]

谁说胖子不能爱 提交于 2019-11-30 10:35:00
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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!