Swift / iOS: How to pass data from AppDelegate to ViewController label?

727 views Asked by At

I've got a (very) basic Universal Links test program that correctly launches from a link to the associated domain. It prints the received URL to the debug console.

in AppDelegate.swift:

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    // First attempt at handling a universal link
    print("Continue User Activity called: ")
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb,
        let url = userActivity.webpageURL {
        //handle URL
        let u = url.absoluteString
        print(u)
  }
    return true
}

ViewController.swift:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var result: UILabel!
      
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        print("Ready ..")
        result.text = "view did load"
   }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

I just want to update the UILabel with the received URL, to show it's working.

I've tried putting the NSUserActivity handler into ViewController, that compiles but doesn't work.

I've tried creating a method in ViewController that I can call from AppDelegate, but don't know how to address it (I'm a Swift beginner).

How can I get the URL to update the UILabel text?

1

There are 1 answers

1
Shehata Gamal On BEST ANSWER

You can do this if it's the root

if let vc = self.window?.rootViewController as? ViewController {
    vc.result.text = u
}

For a complete solution you should get the top most vc with Get top most UIViewController then cast it like above