简体   繁体   中英

Swift - App Delegate not passing data

I'm developing an App that it's data is from a URL, here's a sample code that I'm using 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)

    }

It's is logging the url.host from app delegate. But when i try to log the value of fromUrl from the ViewController.swift it's returning nil . What do you think seems to be the problem? Thanks!

When you declare let appDelegate = AppDelegate() in ViewController you are actually instantiating another instance of AppDelegate . That is not the same instance that you are using as you actual ApplicationDelegate . Try getting that reference by using:

if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
    print(appDelegate.fromUrl)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM