Reputation: 95
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?
}
Upvotes: 1
Views: 312
Reputation: 36304
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.
Upvotes: 1
Reputation: 63
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.
Upvotes: 1