Swift/iOS:如何将数据从AppDelegate传递到ViewController标签? [英] Swift / iOS: How to pass data from AppDelegate to ViewController label?
问题描述
我有一个(非常)基本的通用链接测试程序,该程序可以正确地从指向相关域的链接启动.它将接收到的URL打印到调试控制台.
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.
在AppDelegate.swift中:
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:
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,以显示其正常工作.
I just want to update the UILabel with the received URL, to show it's working.
我尝试将NSUserActivity处理程序放入ViewController中,该处理程序可以编译但不起作用.
I've tried putting the NSUserActivity handler into ViewController, that compiles but doesn't work.
我尝试在ViewController中创建一个可以从AppDelegate调用的方法,但不知道如何解决(我是Swift初学者).
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).
如何获取用于更新UILabel文本的URL?
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
}
对于完整的解决方案,您应该使用获得最高的UIViewController 来获得最高的vc ,然后像上面一样投射
For a complete solution you should get the top most vc with Get top most UIViewController then cast it like above
这篇关于Swift/iOS:如何将数据从AppDelegate传递到ViewController标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!