I created a custom URL scheme to launch my app from other apps. This works from Safari if the app isn't open. It loads AppDelegate with function:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
The issue is that when I have the app open, and place it in the background by hitting the home button. The variable that I have set to receive the text in AppDelegate is not getting hit again. I have a notifier set up in my main VC that works when I bring the app back into the foreground, but the variable that I reference on viewDidLoad is empty since it's reading it from AppDelegate. According to Apple's docs, when a custom url scheme is created, it's going to hit the function above.
The system delivers the URL to your app by calling your app delegate’s application(_:open:options:) method.
There is a function for applicationWillEnterForeground, but I'm not sure how to receive the custom URL into that function if the method isn't called.
Here is what I have so far:
AppDelegate:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var receivedURL: URL?
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
receivedURL = url
return true
}
In MainViewController:
let appDelegate = UIApplication.shared.delegate as? AppDelegate
override fun viewDidLoad() {
if appDelegate?.receivedURL != nil {
urlToDecodeTextView.text = appDelegate?.receivedURL?.absoluteString
}
NotificationCenter.default.addObserver(self, selector: #selector(handleLinks), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func handleLinks(notification: Notification) {
print("made it back") <-- This prints
let test = appDelegate?.receivedURL <-- this is always nil
urlToDecodeTextView.text = test?.absoluteString
}
This is the original code that I had. This code works great if the app isn't open, but not if the app is running in the background. I did notice the appdelegate function is ran everytime, but when the notifier happens, the value is nil - even though it was set in the appdelegate.
What I'm ultimately trying to do is be able to copy a URL from an email (text or URL), and share with my app. When it's shared, my app should open with the url in the appropriate textview. I figured it may be easier to use a custom URL scheme and handle rewriting the link, but this has proven to be a challenge.