在Swift中展开一个简短的URL

时间:2016-01-10 20:39:23

标签: ios swift nsurlsession

如果网址较短https://itun.es/us/JB7h_,您如何将其扩展为完整的网址?

2 个答案:

答案 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
}