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

问题描述

我有一个(非常)基本的通用链接测试程序,该程序可以从指向关联域的链接正确启动。它将接收到的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初学者)。

如何获取用于更新UILabel文本的URL?

解决方法

如果它是根,则可以执行此操作

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

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