Swift / iOS: 如何将数据从 AppDelegate 传递到 ViewController 标签?

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

我有一个(非常)基本的通用链接测试程序,可以从 link 正确启动到相关域。它将收到的 URL 打印到调试控制台。

在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.
    }
    
}

我只想用收到的 URL 更新 UILabel,以表明它正在工作。

我试过将 NSUserActivity 处理程序放入 ViewController,编译但不起作用。

我尝试在 ViewController 中创建一个可以从 AppDelegate 调用的方法,但不知道如何解决它(我是 Swift 初学者)。

如何获取 URL 来更新 UILabel 文本?

如果它是根,你可以这样做

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

对于完整的解决方案,您应该使用 Get top most UIViewController 获得最上面的 vc 然后像上面那样投射它