我试图从url加载我的图像。但是我不明白加载图像的逻辑。我的代码没有呈现出我想要的图像。我在数据库中将photo
的数据类型保存为Data
。
视图:
import SwiftUI
struct profile3: View {
@State private var name = ""
@State private var instagram = ""
@State private var age = ""
@State private var birth = ""
@State private var habit = ""
@State private var live = ""
@State private var head = ""
@State var isActive = false
@ObservedObject var httpClient = HTTPUser()
@ObservedObject var location = LocationManager()
@State var image:UIImage = UIImage()
private func get(){
let defaults = UserDefaults.standard
guard let token = defaults.string(forKey: "value") else {
return
}
httpClient.getper(value: token)
}
var body: some View {
NavigationView{
ZStack{
Image("background")
.resizable()
.scaledToFill()
.frame(minWidth: 0, maxWidth: .infinity)
.edgesIgnoringSafeArea(.all)
if #available(iOS 14.0, *) {
VStack{
Form{
Section(){
ForEach(self.httpClient.per ?? [Per](),id: .id){ person in
NavigationLink(
destination: PhotoView()
){
Image("(person.photo!)")//problem part
}
List{
NavigationLink(
destination: NameView()
.navigationBarTitle(!isActive ? "姓名" : "", displayMode: .inline)
){
Text("姓名 : (person.name!)")
}
NavigationLink(
destination: PictureView()
){
Text("性別 : (person.picture!)")
}
}
}
}.onAppear(perform: {
self.get()
})
}
}
}
else {
// Fallback on earlier versions
}
}
}
}
}
http请求:
import Foundation
class HTTPUser: ObservableObject{
@Published var per: [Per]? = [Per]()
@Published var person: [Per] = [Per]()
func getper(value: String){//登陸後取得用戶資訊
guard let url = URL(string:"http://127.0.0.1:8080/getperinfo") else{
fatalError("URL is not defined")
}
var request=URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("Bearer (value)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request){
(data, response, error) in
guard let data = data, error == nil else{
return
}
let decodePer = try? JSONDecoder().decode([Per].self, from: data)
for value in decodePer!{
DispatchQueue.main.async {
guard let id = value.id else{return}
UserDefaults.standard.setValue(id, forKey: "loginid")
}
}
if let decodePer = decodePer{
DispatchQueue.main.async {
self.per = decodePer
}
}
}.resume()
}
}
模型:
import Foundation
struct Per: Codable{
var id: String?
var name: String?
var account: String?
var picture: String?
var age: String?
var birth: String?
var city: String?
var hobby: String?
var photo: Data?
var user: String?
}
尝试替换
Image("(person.photo!)")//problem part
:
if let photo = person.photo, let img = UIImage(data: photo) {
Image(uiImage: img)
} else {
Image(systemName: "info")
}
不要使用强制解包裹"!"在您的代码中,不为person.photo !不是人名!不是人,是照片!从来没有。
你可能想做的是从数据中创建一个UIImage
,然后用它创建一个SwiftUIImage
视图。*
你应该能够为你的NavigationLink:
做这样的事情NavigationLink(
destination: PhotoView()
){
Image(UIImage(person.photo!)!)
}
然而,我建议你通过提供一个替代视图来正确处理两个强制展开,如果数据没有加载或图像无法解码,否则你的应用程序会崩溃。
*:这假设数据是以UIImage可以解码的方式编码的。它似乎与最常见的图像格式(png, jpg等)工作,所以希望它会为你工作。