'Can't show image from url in swiftUI with URLSession [duplicate]
i'm new to swiftUI and trying to create simple app for showing images from API of images i got the images from url but can't show it in Imageview ,i have button and when i press it , it calls the api and return single image url and i don't figure what the problem is
import SwiftUI
struct ContentView: View {
@ObservedObject var NetworkManager = Network()
var body: some View {
ZStack{
VStack{
ImageDog(UIDogImage:self.NetworkManager.Dog ?? UIImage(systemName: "photo")!)
Button(action: {
self.NetworkManager.ApiCaller()
}) {
Text("GET DOG").font(.system(size: 20)).foregroundColor(Color(#colorLiteral(red: 0.5272222161, green: 0.6115953326, blue: 0.6786056161, alpha: 1))).padding()
}.background(Color(#colorLiteral(red: 0.5401973128, green: 0.9296894073, blue: 0.6209766269, alpha: 1))).cornerRadius(20)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ImageDog: View {
@State var UIDogImage:UIImage
var body: some View {
Image(uiImage:UIDogImage).resizable().frame(width: 200, height: 200, alignment: .center).padding()
}
}
and the Network caller where the image url returned and i change it to image then pass it to Dog property image
import SwiftUI
class Network:ObservableObject {
@Published var Dog:UIImage?
// This Api return random dog images every time you request it
// https://dog.ceo/api/breeds/image/random
// MARK: Network Caller
func ApiCaller(){ // used URLSession for Network requesting and Codable For parsing JSON
// 1 :: create URL
if let DogURL = URL(string: "https://dog.ceo/api/breeds/image/random") {
// 2 :: create URLSession
let session = URLSession(configuration: .default)
// 3 :: give Sesion Task
let Dogtask = session.dataTask(with: DogURL) { (data, response, error) in
if error == nil {
if let DogData = data {
do {
let DogResponseResult = try JSONDecoder().decode(DogResponse.self, from: DogData)
print(DogResponseResult.message!)
if let data = try? Data(contentsOf: URL(string: DogResponseResult.message!)!){
DispatchQueue.main.async {
self.Dog = UIImage(data: data)
}
}
}catch{
print(error)
}
}
}
}
// 4 :: Start Session Task
Dogtask.resume() // Send the request here
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|