简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM