ios - 在 iOS 上的 Swift 中从短 URL 获取完整 URL

标签 ios swift nsurlsession

给定一个短 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)
            }
        }
    }
}

enter image description here

关于ios - 在 iOS 上的 Swift 中从短 URL 获取完整 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710519/

相关文章:

ios - Realm 数组索引超出范围

ios - 如何为 MacOSX 准备一个文件,该文件将被提取到特定目录而不是其他地方?

ios - 如何在 Swift 中将数据从一个 TableView 传递到另一个 TableView ?

ios - Swift 委托(delegate)和可选

ios - 触摸事件不会在部分扩展到父 UIView 之外的子 UIView 之外注册

ios - 如何删除 UISlider 控件左侧的蓝色阴影?

ios - 如何在不导致 iTunes/其他音频上的音乐暂停的情况下播放视频

ios - NSURLSession 多个并发请求被 Exchange 服务器拒绝

ios - (iOS)后台运行下载任务

ios - 在后台下载多个文件(仅限 iOS 7)