给定一个短 URL https://itun.es/us/JB7h_
,如何将其扩展为完整 URL?例如https://music.apple.com/us/album/blackstar/1059043043
最佳答案
扩展
extension URL {
func getExpandedURL() async throws -> Result<URL, Error> {
var request = URLRequest(url: self)
request.httpMethod = "HEAD"
let (_, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
throw URLError.unableToExpand
}
if let expandedURL = response.url {
return .success(expandedURL)
} else {
throw URLError.unableToExpand
}
}
enum URLError: Error {
case unableToExpand
}
}
原始演示
struct ContentView: View {
let shortURL = URL(string: "https://itun.es/us/JB7h_")
@State var expandedURLResult: Result<URL, Error>?
var body: some View {
Form {
Section("Short URL") {
Text(shortURL?.description ?? "")
}
Section("Long URL") {
switch expandedURLResult {
case .some(.success(let expandedURL)):
Text(expandedURL.description)
case .none:
Text("Waiting")
case .some(.failure(let error)):
Text(error.localizedDescription)
}
}
}
.task {
do {
expandedURLResult = try await shortURL?.getExpandedURL()
} catch {
expandedURLResult = .failure(error)
}
}
}
}
关于ios - 在 iOS 上的 Swift 中从短 URL 获取完整 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710519/