Search code examples
swiftuiios-universal-links

Open via universal link doesn't toggle bool on device


I have a pretty easy code solution, that opens the app as it should. The Associated Domains and the apple-app-site-association file all work, but if I have a variable in there, or even a print statement, it won't get called. To be even more weird, it does all the things expected on the simulator using RocketSim's DeepLink feature.

So with everything setup and this small code, the app opens perfectly, except the debugPrint statements or the .toggle, only in the simulator:

struct ContentView<ViewModel: ContentViewModelProtocol>: View {
    @StateObject private var viewModel: ViewModel

    init(viewModel: @autoclosure @escaping () -> ViewModel = ContentViewModel()) {
        self._viewModel = StateObject(wrappedValue: viewModel())
    }

    var body {
        // just some basic view structure

        .onOpenURL { url in
            debugPrint("Received URL onOpenUrl: \(url)")
            handleUniversalLink(url: url)
        }
    }
    
    private func handleUniversalLink(url: URL) {
        debugPrint("Received URL handleUniversalLink: \(url)")
        
        let path = url.path
        
        if path.starts(with: "/test") {
            viewModel.isSheetPresented.toggle()
        }
    }
}

protocol ContentViewModelProtocol: ObservableObject {
    var isSheetPresented: Bool { get set }
}

class ContentViewModel {
    @Published var isSheetPresented = false
}

I have put this code in the @Main, on the ContentView, doesn't care. It just doesn't give me any information using it with an actual device.

If I have a sepcific tab switch based on the url inside handleUniversalLink, somehow it works, but a toggle or a print statement don't.

What am I doing wrong here?


Solution

  • The answer seems to be this one: https://forums.developer.apple.com/forums/thread/674141

    Via a link (browser) it just worked and camera needed the other function from the apple forum:

    .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { userActivity in
            print("Continue activity \(userActivity)")
            guard let url = userActivity.webpageURL else {
                    return
            }
            print("User wants to open URL: \(url)")
            // TODO same handling as done in onOpenURL()
    }