8

What URL exactly we need to specify inside .widgetURL()?

In WWDC sessions on Widget Code Along, They used .widgetURL(entry.character.url). Here entry.character.url is URL(string: "game:///egghead")!

Please explain about URL we need to pass here (widgetURL()) to reach the particular view of APP?

2

1 Answer 1

8

the url is in the form scheme://someAction

At risk of oversimplifying it, the scheme is typically the name of your app. this is how you confirm that the url is intended for your app

in your widget body you use the widgetURL modifier:

var body: some View {
        content().widgetURL("myApp://someAction")
}

then in your app you use the onOpenURL modifier to pick up the url, check its for your app and parse it to determine what to do. someAction is the message you are sending the app to tell it what to do

 var body: some Scene {
        WindowGroup {
            ContentView()
                .onOpenURL { url in
                    guard url.scheme == "myApp" else { return }
                    print(url) // parse the url to get someAction to determine what the app needs do
                }
        }
    }

I usually make the url of the form myApp://someAction/parms so that I can parse the url to determine what the app needs to do and also pass it some parms. Some people like to do this by forming the URL properly with URLComponents - path, queryItems etc. this is probably best practice.

Sign up to request clarification or add additional context in comments.

4 Comments

How does a particular view of the app opens on click of the widget? As you are using .onOpenURL, then how exactly this block of code is implemented? I am actually stuck at this point only.
use the code provided to implement. its an iOS method.nothing more to do.
What if the widget has to open different screens based on the button they tapped on the widget? In such case, widgetURL is set inside the contentView?
Change the someAction component of the url to a different action. Then parse the url in onOpenUrl to figure out which action was instigated and open the relevant screen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.