【发布时间】:2022-02-01 12:53:36
【问题描述】:
给定一个短 URL https://itun.es/us/JB7h_,如何将其扩展为完整 URL?例如https://music.apple.com/us/album/blackstar/1059043043
【问题讨论】:
-
您可能应该添加一些说明,说明这是一个问答式问题,这样它就不会因为过于宽泛而被关闭
标签: ios swift nsurlsession
给定一个短 URL https://itun.es/us/JB7h_,如何将其扩展为完整 URL?例如https://music.apple.com/us/album/blackstar/1059043043
【问题讨论】:
标签: ios swift nsurlsession
最终解析的 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
}
【讨论】:
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()
}
}
}
【讨论】: