Passing Data from App Delegate to View Controller

How to pass data from appdelegate to a viewcontroller?

OK - you've got most of the work already done...

When using segues, iOS creates your view controller and gives you access to it in prepare, where you probably have done something like this:

if let vc = segue.destination as? detailPinViewController {
vc.myVariable = "this is the data to pass"
}

In didFinishLaunchingWithOptions, you are doing the creation part, and the "presentation" part... so you can just add in the "pass the data" part:

let destinationViewController = storyboard.instantiateViewController(withIdentifier: "detailPin2") as! detailPinViewController

destinationViewController.myVariable = "this is the data to pass"

let navigationController = self.window?.rootViewController as! UINavigationController

navigationController.pushViewController(destinationViewController, animated: false)

and that should do it.

Passing Data from App delegate to View Controller

Interface:

@interface MyAppDelegate : NSObject  {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString;
...
@end

and in the .m file for the App Delegate you would write:

@implementation MyAppDelegate
@synthesize myString;
myString = some string;
@end

Then, in viewcontroller.m file you can fetch:

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
someString = appDelegate.myString; //..to read
appDelegate.myString = some NSString; //..to write

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

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

Pass data from AppDelegate to ViewController in realTime (iOS) Swift 2

You wrote below line is right in ViewController in viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.refreshView), name: "AnyThingYouWant", object: nil)
}

But Add this line in appDelegate where you want to call ViewController.refreshView method

NotificationCenter.default.post(name: "AnyThingYouWant", object: self)
}

if you want to call refreshView method when got notification then write above line in didReceiveLocal/RemoteNotification Method

Passing data from Scene Delegate to ViewController when opening app with URL

Managed to fix it by initialising the controller again and updating the root controller.

// SceneDelegate

func changeRootViewController(_ vc: UIViewController, animated: Bool = true)
{
guard let window = self.window else {
return
}
window.rootViewController = vc
}

//Reinitialise

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationNavigationController = storyboard.instantiateViewController(withIdentifier: "ViewController2")
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(destinationNavigationController)

Swift Passing data from appDelegate to another class

There are several patterns you can use to achieve what you want

  1. You could access the AppDelegate through the UIApplication:

    let delegate = UIApplication.sharedApplication().delegate as AppDelegate
    let deviceToken = delegate.deviceToken
  2. Look into singletons. A quick google search for 'Swift singleton' will get you a long way. The first result:

    class SingletonB {

    class var sharedInstance : SingletonB {
    struct Static {
    static let instance : SingletonB = SingletonB()
    }
    return Static.instance
    }
    }

Then use sharedInstance to instantiate the singleton anywhere and access the same variables.

The first one is quick and dirty, so for more serious projects I would recommend the singleton pattern.

There are probably a million ways to do this, but this should get you started

(More at this link, which explores a few ways to implement singletons: https://github.com/hpique/SwiftSingleton )

Passing an object to a ViewController from AppDelegate

  • In AppDelegate create a property

    private weak var viewController : ViewController?
  • In the view controller in viewDidLoad assign self to that property

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.viewController = self

Now you can access the view controller from AppDelegate

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



Related Topics



Leave a reply



Submit