How to open a specific View Controller from Today Widget?
Asked Answered
C

1

5

I'm creating a simple today widget which contains one button, this button should - when pressed - open a specific View Controller in my corresponding application.

The only solution I've thought of was to create a URL type which can only open the initial view controller (at least to my knowledge).

Below is the code I'm currently using inside the UIButton action:

   var url = NSURL(string: "_my_url_://")
    extensionContext?.openURL(url!, completionHandler: nil)
Chemosynthesis answered 4/4, 2015 at 9:56 Comment(0)
I
8

You can create a URL type for your app (say myapp://) and parse the part after the host name. So for example myapp://signupform or myapp://activities/15. You have the flexibility to make those URLs whatever you want. You can't really tie URL types to specific VCs (automatically), you have to do the work of reading the URL and swapping out VCs in your app delegate.

When you do this you'll then need to parse this URL in your app delegate. You'll get called on your app delegate with the method application:openURL:sourceApplication:annotation: (docs) when your app is opened via a URL, and you can inspect the URL for whatever items you need.

Based on looking at the URL you'll then manually manipulate the nav stack based on which view controller you need to show. So for example you might grab a view controller from your storyboard and add that in, or you might just switch to a given tab in your tab bar controller, or you might back out all the current view controllers to your root screen before you do anything. Unfortunately those actions don't have a universal answer and it all depends on what exactly you're trying to do.

Incipit answered 4/4, 2015 at 14:10 Comment(5)
I've tried that and implemented application:openURL:sourceApplication:annotation but weirdly, it doesn't get called. (and google isn't helpful either)Chemosynthesis
But your app gets launched? Strange. I made a quick reference app that you might be able to poke at (likely something under the "info" tab of your project). If you type myapp:// into safari you'll see it launch that callback method. cl.ly/0H3h2Q2n3b0VIncipit
Yes exactly, it gets launched, but it just displays the initial view controller.Chemosynthesis
Yeah, it will always launch the first VC (or, if the app is already running, just multi-task switch to the app w/ whatever screen was last open), that's why you need to inspect the URL in that app delegate method and then manually add whatever VCs you need to the stack.Incipit
Here's an updated version that shows grabbing a view controller and adding it to the nav stack when the app is opened via the scheme (vs a normal open): cl.ly/233C1B180k1B, maybe that'll help?Incipit

© 2022 - 2024 — McMap. All rights reserved.