OK. We have managed to give our apps a URL Scheme, so they can be opened, using a simple URL. But we aren’t actually doing anything with the URL, besides starting the app.
We have also avoided doing any coding. Time to change things up, and get coding. It will be quite simple, and all the action will happen in the SimpleAppDelegate.swift
file.
Where We Are Now
We have implemented “Deep Links,” at their most basic level, where the app is opened, via a URL that specifies “iul[1...3]
“, as the service.
But we aren’t doing anything about it. The app is simply being launched. We’ll need to add code to the app delegates/app type, in order to parse the URLs.
Where to Go Next
UIKit (App and Scene Delegate apps)
In UIKit, we’ll need to add some delegate methods to the app, in order to “catch” the URL we were opened with. At that point, we can parse it, and figure out what it wants us to do.
There are two types of calls that can be made:
- Open the App From a “Cold Start” The app is not currently running, so it needs to be started “from scratch.”
- Bring A Background App to the Front The app is still running, but is in the background.
Each of these can be handled individually, or we can use a single app delegate call to handle both.
App Delegate Support
In the Simple App Delegate target, all the code changes will be applied to the AppDelegate
class, in the SimpleAppDelegate.swift
file.
Adding URL support to a standard App Delegate app is quite simple.
Adding An Open Handler
Under the “didFinishLaunchingWithOptions
” method, add the following code:
func application(_: UIApplication, open inURL: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { var status: AppStatus = .off if let statusString = inURL.query(), let tempStatus = AppStatus(rawValue: statusString) { status = tempStatus } currentViewController?.updateUI(status: status) return true }
What this does, is add a delegate responder (application(_: UIApplication, open: URL, options: [OpenURLOptionsKey: Any])
), that will get called, whenever the app is opened. This works for both a “cold start,” and a foreground.
If there is a supplied URL, we parse out the query (after the question mark), and feed it directly into our enum, as a rawValue. This means that we are case-sensitive. It wouldn’t be a big deal to add a lowercased()
to it, but I’m keeping things as simple as possible, for this tutorial.
It should be noted that we need to refresh the screen. This method is called after the view has been instantiated. That’s handled by the currentViewController?.updateUI(status: status)
call.
The Result
Now, you can enter the new URL Scheme URLs (for the Universal-App app), into Safari or Notes, and open the app with them:
iul1://?off
All circles are grayiul1://?stop
The leftmost circle is rediul1://?caution
The center circle is yellowiul1://?go
The rightmost circle is green
This is the release that has the code, up to this point.
Scene delegates need a bit more work. We’ll tackle that, next.