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

情到浓时终转凉″ 提交于 2021-01-29 11:07:18

问题


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.

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:

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

I just want to update the UILabel with the received URL, to show it's working.

I've tried putting the NSUserActivity handler into ViewController, that compiles but doesn't work.

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).

How can I get the URL to update the UILabel text?


回答1:


You can do this if it's the root

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

For a complete solution you should get the top most vc with Get top most UIViewController then cast it like above



来源:https://stackoverflow.com/questions/64162820/swift-ios-how-to-pass-data-from-appdelegate-to-viewcontroller-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!