2 years ago

#56698

test-img

Abv

Why does the SwiftUI canvas doesn't update from a UserDefault string and does when running simulator?

There is a difference between when I launch with the simulator or look at the canvas.

There is a stored value for key "igBId" in userDefault and the value shows when launching the simulator, however when looking at the canvas, it doesn't.

Anyone knows why in the case of canvas, it doesn't catch the value that's in userDefault?

enter image description here

This is my code:

import SwiftUI

let n = UserDefaults.standard.string(forKey: "IgBId") ?? "?"

struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        List {
            ForEach(viewModel.dataMedias, id: \.self){
                media in
                    HStack{
                        Text("\(media)")
                    }
                }
            }
        .onAppear {
            viewModel.fetch2()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class ViewModel: ObservableObject {
    @Published var dataMedias: [String] = []
    func fetch2() {
        fUrl(Completion: { [weak self](result) in
            self?.dataMedias = [result]
       })
    }
    
    func fUrl (Completion block: @escaping((String) -> ())) {
        let url = "https://\(n)"
            block(url)
    }
}

ios

swift

canvas

swiftui

userdefaults

0 Answers

Your Answer

Accepted video resources