我试图将URL中的图像显示为TabView的tabItem。我用SDWebImageSwiftUI尝试了一下,但是那没用,所以我现在要尝试的是将图像存储在文档目录中,然后从中加载为UIImage。
这是我到目前为止编写的代码,但是没有用。但是,如果我加载系统映像,则可以正常工作。
import SwiftUI
import Alamofire
struct ContentView: View {
var body: some View {
TabView {
VStack {
Text("Hello")
}
.onAppear(perform: {
self.saveAvatarImage(fromUrl: "https://gmsrp.cachefly.net/images/20/05/15/65e1de275864fb9c73b7be374315481a/960.jpg")
})
.frame(maxWidth:.infinity,maxHeight: .infinity)
.tabItem {
Image(uiImage: getAvatarImage() ?? UIImage.init(systemName: "star.fill")!)
.frame(width:20,height: 20)
}
}
}
func avatarFolderUrl() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Avatar", isDirectory: true)
}
func saveAvatarImage(fromUrl url:String) {
guard let avatarUrl = URL.init(string: url) else {
return
}
DispatchQueue.global().async {
let destination: DownloadRequest.Destination = { _, _ in
let documentsURL = self.avatarFolderUrl()
let fileURL = documentsURL.appendingPathComponent("avatar.jpg")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
AF.download(URLRequest.init(url: avatarUrl), to: destination)
.response { (response) in
switch response.result {
case .success:
let documentsURL = self.avatarFolderUrl()
let fileURL = documentsURL.appendingPathComponent("avatar.jpg")
if FileManager.default.fileExists(atPath: fileURL.path) {
if let image = UIImage.init(contentsOfFile: fileURL.path) {
if let compressedImageData = image.jpegData(compressionQuality: 1.0) {
try? compressedImageData.write(to: fileURL)
}
}
}
case .failure(let error):
debugPrint("Failed to download : \(error)")
}
}
}
}
func getAvatarImage() -> UIImage? {
let documentsURL = avatarFolderUrl()
let fileURL = documentsURL.appendingPathComponent("avatar.jpg")
if FileManager.default.fileExists(atPath: fileURL.path) {
if let image = UIImage.init(contentsOfFile: fileURL.path) {
debugPrint("Loading Profile From \(fileURL.path)")
return image
}
}
return nil
}
}
这里是上面代码的输出。它显示的是蓝色视图,而不是图像。正确的方法是加载系统映像。