Expand a short URL in Swift [closed]

2020-02-26 15:03发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago.

Given a short URL https://itun.es/us/JB7h_, How do you expand it into the full URL?

回答1:

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
})


回答2:

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
}