在Swift中展开一个简短的URL

Zel*_*lko 2 ios nsurlsession swift

给定一个简短的URL https://itun.es/us/JB7h_,如何将其扩展为完整的URL?

Zel*_*lko 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()
    }
}
Run Code Online (Sandbox Code Playgroud)

let shortURL = NSURL(string: "https://itun.es/us/JB7h_")

shortURL?.expandURLWithCompletionHandler({
expandedURL in
    print("ExpandedURL:\(expandedURL)")
    //https://itunes.apple.com/us/album/blackstar/id1059043043
})
Run Code Online (Sandbox Code Playgroud)


jtb*_*des 5

最终解析的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
}
Run Code Online (Sandbox Code Playgroud)