簡體   English   中英

Swift / iOS:如何將數據從 AppDelegate 傳遞到 ViewController 標簽?

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

我有一個(非常)基本的通用鏈接測試程序,它可以從鏈接到關聯域正確啟動。 它將接收到的 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
}

視圖控制器.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 然后像上面一樣投射它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM