SwiftUI 问答之从本地主机上的 url 加载图像

实战需求

我试图从 url 加载我的图像。但我不明白加载图像的逻辑。而且我的代码没有显示我想要的图像。我将 myphoto的数据类型保存为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!不适用于person.name!,不适用于person.picture!。绝不。


精品教程推荐


加入我们一起学习SwiftUI

QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com

发表回复