用户默认不将值存储在didFinishLaunchingWithOptions方法Swift中

时间:2019-05-19 19:38:56

标签: swift

我正在尝试在Userdefault启动时使用application存储一些值。在这里,我将用户默认存储代码放置在appdidfinishlaunching方法内,并试图将值放入主viewcontroller中。应用程序第一次启动时,它没有接收到值,但是第二次我接收到values。该如何解决?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        if ((UserDefaults.standard.object(forKey: "From_Name") == nil) && (UserDefaults.standard.object(forKey: "To_Name") == nil)) {

            // Override point for customization after application launch.
            UserDefaults.standard.set("0", forKey: "DFrom_ID") //setObject
        }

我的MainViewController

 override func viewDidLoad() {
        super.viewDidLoad()

        print("\(UserDefaults.standard.string(forKey: "DFrom_ID"))")

        return true
    }

1 个答案:

答案 0 :(得分:0)

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated);
    print("\(UserDefaults.standard.string(forKey: "DFrom_ID"))")
}

在MainViewController中将代码从ViewDidLoad删除到ViewDidAppear方法。