【问题标题】:Get full URL from short URL in Swift on iOS从 iOS 上的 Swift 中的短 URL 获取完整 URL
【发布时间】:2022-02-01 12:53:36
【问题描述】:

给定一个短 URL https://itun.es/us/JB7h_,如何将其扩展为完整 URL?例如https://music.apple.com/us/album/blackstar/1059043043

【问题讨论】:

  • 您可能应该添加一些说明,说明这是一个问答式问题,这样它就不会因为过于宽泛而被关闭

标签: ios swift nsurlsession


【解决方案1】:

最终解析的 URL 将在 NSURLResponse 中返回给您:response.URL

您还应该确保使用 HTTP HEAD 方法以避免下载不必要的数据(因为您不关心资源主体)。

Swift 4.2 更新:

extension URL {
func resolveWithCompletionHandler(completion: @escaping (URL) -> Void) {
    let originalURL = self
    var req = URLRequest(url: originalURL)
    req.httpMethod = "HEAD"

    URLSession.shared.dataTask(with: req) { body, response, error in
        completion(response?.url ?? originalURL)
        }.resume()
}

旧 Swift 版本:

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
}

【讨论】:

  • 好的,它可以工作,但是,你如何取消任务?
【解决方案2】:

扩展

   extension URL {
    func getExpandedURL() async -> URL? {
        var request = URLRequest(url: self)
        request.httpMethod = "HEAD"
        let data = try? await URLSession.shared.data(for: request)
        return data?.1.url
    }
}

示例

struct ContentView: View {
    let shortURL = URL(string: "https://itun.es/us/JB7h_")
    @State var expandedURL: URL?
    
    var body: some View {
        Form {
            Section("Short URL") {
                Text(shortURL?.description ?? "")
            }
            
            Section("Long URL") {
                Text(expandedURL?.description ?? "")
            }
        }
        
        .task {
            expandedURL = await shortURL?.getExpandedURL()
        }
    }
    
}

【讨论】:

  • 这个完成处理程序的使用格式不正确,因为它在错误情况下从未被调用。
  • 为 Swift 5.5 更新和简化
猜你喜欢
  • 2017-05-11
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 2012-10-26
  • 2011-10-09
  • 2013-04-08
相关资源
最近更新 更多