Home iOS Development swift – Swiftui .sheet presentation after await doesn’t refresh view with optional input in iOS 17

swift – Swiftui .sheet presentation after await doesn’t refresh view with optional input in iOS 17

0
swift – Swiftui .sheet presentation after await doesn’t refresh view with optional input in iOS 17


I’ve a project that is using core data, there is a detailview that is using a observed object, if I create a new item, first I create the new Item and after I send it in the detail view. In ios16 was working well, in ios 17 it seems that the view doesn’t read the variable created (it is nill and crashs).
To understand the issue, I simplified with an easy code to understand the problem.
I understood that if I put if variable != nil it force to refresh the view and the TestVar2View(variable: variable!) now is using the correct variable populated.

XCODE 15.0 iOS 17.0

struct TestVar2View: View {
    var variable: String
    var body: some View {
        Text(variable)
    }
}


struct ContentView: View {
    @State var isOn = false
    @State var show = false
    @State var variable: String?
    
    var body: some View {
        VStack (spacing: 20) {
            Text("\(isOn ? "on":"off")")
            
            //********************
            //WITH THIS, ALL IS WORKING
//            if variable != nil {
//                Text("damn")
//            }
            //********************
            
            Button(action: {
                Task {//CRASH
                    isOn = true
                    variable = await createString()
                    show = true
                }
            }, label: {
                Text("VERSION 1 crash")
                    .bold()
            })
            Button(action: {
                Task { //WORKING
                    isOn = await createOnAndString()
                    show = true
                }
            }, label: {
                Text("VERSION 2 OK")
                    .bold()
            })
        }
        .sheet(isPresented: $show, content: {
            NavigationView {
                VStack {
                    Text("SHEET \(isOn ? "on":"off")")
                    TestVar2View(variable: variable!) //VERSION 1 crash variable = nil
                        .id(variable) //doesen't work
                }
            }
        })
    }
    
    func createString() async -> String {
        try? await Task.sleep(nanoseconds: 1_000_000_000)
        return "CREATED"
    }
    func createOnAndString() async -> Bool {
        variable = await createString()
        return true
    }
}

#Preview {
    ContentView()
}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here