Swift/iOS:如何将数据从 AppDelegate 传递到 ViewController 标签? [英] Swift / iOS: How to pass data from AppDelegate to ViewController label?

查看:24
本文介绍了Swift/iOS:如何将数据从 AppDelegate 传递到 ViewController 标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

如果是root就可以了

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆