1

I tried to load my image from url. But I don't understand the logic of loading image. And my code doesn't present the image I want. I saved my photo's data type as Data in the database.

view:

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 request:

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()
            }
    }

model:

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?
    
}

2 Answers 2

1

try replacing

Image("\(person.photo!)")//problem part

with:

if let photo = person.photo, let img = UIImage(data: photo) {
    Image(uiImage: img)
} else {
    Image(systemName: "info")
}

DO NOT use the force unwraps "!" in your code, not for person.photo! not for person.name!, not for person.picture!. NEVER.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey, thanks for helping. But it seems that I can't get the Image because I get an "i" on my view. And I posted my question wrong. I saved my photo type as a Data in the database. Should I save it as a string? And I'm sure that I had stored a photo in my database.
when you save your UIImage data use, myimage.pngData(). Do you actually get some image data from your request? or is it nil?
Sorry for being late. And I get "2964202 bytes" when I print my photo. Is this the right thing that I should get?
looks right to me. Did you get it working now?
1

What you probably want to do is create a UIImage from the data, then create a SwiftUI Image View with it.*

You should be able to do something like this for your NavigationLink:

NavigationLink(
    destination: PhotoView()
){
    Image(UIImage(person.photo!)!)
}

However I would recommend you properly deal with the two force unwraps by providing an alternative view if the data isn't loaded or the image fails to decode since otherwise your app will crash.

*: This assumes that the data is encoded in a way that UIImage can decode. It seems to work with most common image formats (png, jpg, etc.) so hopefully it will work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.