Swift - App Delegate 不传递数据
Swift - App Delegate not passing data
我正在开发一个应用程序,它的数据来自 URL,这是我正在使用的示例代码
AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var fromUrl: String!
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject)-> Bool {
print("Host: \(url.host!)")
self.fromUrl = url.host!
return true
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let appDelegate = AppDelegate()
override func viewDidLoad() {
super.viewDidLoad()
print(appDelegate.fromUrl)
}
正在记录来自应用程序委托的 url.host
。但是当我尝试从 ViewController.swift
中记录 fromUrl
的值时,它返回 nil
。你认为问题是什么?谢谢!
当您在 ViewController
中声明 let appDelegate = AppDelegate()
时,您实际上是在实例化 AppDelegate
的另一个实例。这与您实际使用的实例 ApplicationDelegate
不同。尝试使用以下方式获取该参考:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
print(appDelegate.fromUrl)
}
我正在开发一个应用程序,它的数据来自 URL,这是我正在使用的示例代码 AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var fromUrl: String!
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject)-> Bool {
print("Host: \(url.host!)")
self.fromUrl = url.host!
return true
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let appDelegate = AppDelegate()
override func viewDidLoad() {
super.viewDidLoad()
print(appDelegate.fromUrl)
}
正在记录来自应用程序委托的 url.host
。但是当我尝试从 ViewController.swift
中记录 fromUrl
的值时,它返回 nil
。你认为问题是什么?谢谢!
当您在 ViewController
中声明 let appDelegate = AppDelegate()
时,您实际上是在实例化 AppDelegate
的另一个实例。这与您实际使用的实例 ApplicationDelegate
不同。尝试使用以下方式获取该参考:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
print(appDelegate.fromUrl)
}