【问题标题】:Swift / iOS: How to pass data from AppDelegate to ViewController label?Swift / iOS:如何将数据从 AppDelegate 传递到 ViewController 标签?
【发布时间】:2021-01-17 14:46:30
【问题描述】:

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

【问题讨论】:

    标签: ios swift appdelegate nsuseractivity


    【解决方案1】:

    如果是根目录,你可以这样做

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

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

    【讨论】:

    • 谢谢。现在好像在模拟器上显示不同的链接OK。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2017-11-08
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多