I am trying to figure out why a breakpoint triggered just once for the first time I used my app and when I did the same steps one more time the breakpoints triggered twice for the same line of code, nothing changed on runtime I just used navigation forward and back. I demo this issue with a comment on my video below. It's 5 minutes video with explanation, but you will see the issue in 2 minutes:
here is a link to a video I made https://youtu.be/s3fqJ4YhQEc
If you don't want to watch a video I will add a code at the bottom of the question:
here is a link to a repo I used to record a video: https://github.com/matrosovDev/SwiftUINavigatioPopBackIssue
I am also use Apple Feedback Assistant, so guys help me with this as well. I assumed that there is something with deallocating view that was not deallocated in a right way but they answered with this:
There is no notion of “deallocating” structs in Swift. SwiftUI manages view lifetimes. If you’re writing code that somehow depends on the existance or non-existance of a particular View at a particular point in time, that code is wrong.
What leads you to believe that the SecondView isn’t “deallocated”? The code that leads you to that conclusion is making incorrect assumptions about the SwiftUI view lifecycle.
Anyway you may see on the video breakpoints triggered twice and even before I actually showing SecondView
.
Code example:
struct FirstView: View {
@EnvironmentObject var simpleService: SimpleService
@State var showSecondView = false
var body: some View {
NavigationView {
ZStack {
Button(action: {
self.downloadImageFromURL()
}) {
Text("Next")
.fontWeight(.bold)
.font(.title)
.padding(EdgeInsets(top: 20, leading: 40, bottom: 20, trailing: 40))
.background(Color.blue)
.cornerRadius(8)
.foregroundColor(.white)
}
NavigationLink(destination: SecondView(), isActive: $showSecondView) { EmptyView() }
}
}
}
func downloadImageFromURL() {
simpleService.image = nil
if let url = URL(string: "https://placebear.com/200/300") {
simpleService.downloadImage(from: url) { (image) in
self.showSecondView = true
}
}
}
}
struct CircleImage: View {
var image: Image
var body: some View {
image
.resizable()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
.aspectRatio(contentMode: .fill)
}
}
struct SecondView: View {
@EnvironmentObject var simpleService: SimpleService
var body: some View {
NavigationView {
CircleImage(image: simpleService.image!) // Called twice next time I visit SecondView
.frame(height: 140)
.frame(width: 140)
}.onAppear(perform: fetch)
}
private func fetch() {
print(Date())
}
}