Swift: How to Access in Appdelegate Variable from the View Controller

Access variables from App Delegate in View Controller

The error message have told you property initializers run before 'self' is available.

Maybe you should initialize it in viewDidLoad

let delegate = UIApplication.shared.delegate as! AppDelegate
var user: String?
var firstName: String?
var lastName: String?

override func viewDidLoad() {
super.viewDidLoad()

user = delegate.userID
firstName = delegate.givenName
lastName = delegate.familyName
}

How to access ViewController variable from AppDelegate

You need get the rootViewController

func applicationDidEnterBackground(_ application: UIApplication) {

let viewController = self.window?.rootViewController as? ViewController
print(viewController?.animal)

}

How do I access the UIApplicationDelegate from any particular view controller?

When you say "within the AppDelegate", do you mean as an instance property? If the app delegate class is AppDelegate, then the instance of it is UIApplication.shared.delegate as! AppDelegate, and any instance properties it may have can be access through that reference.

But if you simply mean "in the file AppDelegate.swift but outside the AppDelegate class itself", then this variable is a global and can be accessed directly from anywhere.

Access variable of Viewcontroller in AppDelegate

Try to add an observer in your view controller:

NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillTerminate),
name: .UIApplicationWillTerminate,
object: nil)

using callback:

@objc func applicationWillTerminate() {
// Disconnect socket

}

Also I think everything will be disconnected when app terminates

Pass a variable from AppDelegate to other ViewController

You can create a var inside the AppDelegate

var fcmToken:String?

assign it inside the callback , then access it with in any vc

let de = UIApplication.shared.delegate as! AppDelegate 
if let token = de.fcmToken {

}

The problem with your current solution is that posting the notification may occur before the vc is shown ( means before it registers as an observer so it will loss the token )


You can observe the changes with

   var tokenTimer:Timer!  // why timer ? as sometimes token changed and firInstanceIDTokenRefresh not fired also you can get rid of firInstanceIDTokenRefresh  implementation 

// put these inside AppDelegate didFinishLaunching...
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
self.tokenTimer = Timer.scheduledTimer(timeInterval:0.3,
target: self,
selector: #selector(self.checkToken),
userInfo: nil,
repeats: true)

@objc func checkToken()
{
if let refreshedToken = FIRInstanceID.instanceID().token() {

print("retrieved \(refreshedToken)")

fcmToken = refreshedToken
}
else{

print("not retrieved yet")


}
}
@objc func tokenRefreshNotification(_ notification: Notification) {

if let refreshedToken = FIRInstanceID.instanceID().token() {

print("retrieved \(refreshedToken)")

fcmToken = refreshedToken
}
}

Sometimes firebase glitches and delay sending the token , so it's a recommended way to send the token to your server every launch of app to keep track of refresh and possibility of nil uploaded token before

Access current instance of view controller from app delegate in swift?

You have two options, the second one is better by design.

First option: (what you want)

I don't know the structure of your view controllers, so let me assume you have a root view controller, you could get it from AppDelegate via:

rootVC = self.window?.rootViewController

And if you want to get the presented view controller from the root view controller (like many apps, the presented view controller is a tab bar controller):

guard let tabBarController = rootVC.presentedViewController as? TabBarController else {
return
}

Once you get your tab bar controller, you can find the view controller in the array of view controllers:

tabBarController.viewControllers

Essentially, what I'm trying to say is you have to jump through your view controllers starting from the root to get to the controller you want, then grab the variable from there. This is very error prone, and generally not recommended.

Second option (better practice):

Have your view controller register as an observer for the UIApplicationWillResignActiveNotification notification. This will allow you to do whatever you want from the view controller when your app is about to enter background.

In swift , how to implement a variable in the app delegate, in order to retrieve it everywhere in the app?

1 . Create the instance of your "Personne" Class in AppDelegate
( var persnee = Personne())

2 . create a function in your AppDelegate to which will return instance of AppDelegate

class func appDelegate() -> AppDelegate
{

return UIApplication.shared.delegate as! AppDelegate

}

3 . You can call like this

AppDelegate.appDelegate(). persnee

global variable in appdelegate swift4

You need to understand in what scope you declare a variable and how it is visible outside that scope. Now your variable is only visible inside that func, to make it visible to your view controller it needs to be a class property in AppDelegate.

So define a property like (somewhat simplified code here)

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var refreshedToken = InstanceID.instanceID().token()
...

}

And then in you can access it in your view controller

let token = appDelegate.refreshedToken


Related Topics



Leave a reply



Submit