如何解决如何在 SwiftUI 中处理 URL 重定向?
import SwiftUI
struct ContentView: View {
@State var website = "https://www.stackoverflow.com/favicon.ico"
@State var favicon : String?
var body: some View {
vstack {
if favicon != nil {
Image(uiImage: favicon!.toImage()!)
}
TextField("Sito",text: $website).padding()
Button(action: {
website = "https://www." + website + ".com/favicon.ico"
},label: {
Text("Complete URL")
}).padding()
Button(action: {
if let url = URL(string: website) {
let session = URLSession.shared.dataTask(with: url) { [self] (data,response,error) in
if let error = error {
debugPrint(error.localizedDescription)
return
}
if let data = data {
var immagineTemp : UIImage = UIImage(systemName: "questionmark")!
if UIImage(data: data) != nil {
immagineTemp = UIImage(data: data)!
} else {
debugPrint("URL was redirected")
}
favicon = immagineTemp.toString()
}
}
session.resume()
}
},label: {
Text("Get favicon")
}).padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension String {
func toImage() -> UIImage? {
if let data = Data(base64Encoded: self,options: .ignoreUnkNownCharacters){
return UIImage(data: data)
}
return nil
}
}
extension UIImage {
func toString() -> String? {
let data: Data? = self.pngData()
return data?.base64EncodedString(options: .endLineWithLineFeed)
}
}
通常,var 网站是空的,可以通过 TextField 填充,但为了这个例子的目的,我用那个 URL 填充它,因为如果你使用 Stackoverflow 网站下载 favicon,就像我在代码中写的上面,它不起作用,因为 URL“https://www.stackoverflow.com/favicon.ico”将您重定向到“https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v =ec617d715196",这是 Stackoverflow 图标所在的位置。因此,“immagineTemp = UIImage(data: data)!”结果为零,它位于括号中,那里有 debugPrint("URL was redirected").
我希望它做的是自动检测一个 URL 将您重定向到另一个 URL 的事实,以便它可以继续自己下载网站图标。有办法吗?
解决方法
起初我以为您可以将响应(类型为 URLResponse
)转换为 HTTPURLResponse
,然后检查该对象的属性 statusCode
。
但经过进一步检查,似乎可行的方法是实现 NSURLSessionTaskDelegate
,更具体地说是以下方法:
optional func urlSession(_ session: URLSession,task: URLSessionTask,willPerformHTTPRedirection response: HTTPURLResponse,newRequest request: URLRequest,completionHandler: @escaping (URLRequest?) -> Void)
请参阅此处的 Apple 文档:https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/1411626-urlsession
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。