在iOS上的SWIFT中从短URL获取完整URL

2022-09-01 ios swift nsurlsession
给定一个简短的URLhttps://itun.es/us/JB7h_,如何将其展开为完整的URL?例如https://music.apple.com/us/album/blackstar/1059043043


解决方案

扩展

   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数组

2023-07-19 swift 数组