2016-11-29 13 views
0

我有一個UserDefaults bool值,它告訴我何時必須在應用程序的第一次安裝時顯示我的演練。安裝時,我的鍵「firstAccessToApp」的布爾值從true爲假,但如果我從我的設備中刪除應用程序並重新安裝它,我的演練不會顯示,因爲bool值仍然是false。如何從設備中刪除我的應用程序時更改值?這是我的代碼:刪除應用程序時更改UserDefaults布爾值

if !defaults.bool(forKey: "firstAccessToApp") { 
     present(Walkthrough(), animated: true, completion: nil) 
     UserDefaults.standard.set(true, forKey: "firstAccessToApp") 
     UserDefaults.standard.synchronize() 
    } 

回答

1

當你安裝一個應用程序,關鍵並不在UserDefaults存在,如果您嘗試訪問它,它就會返回默認值,這是false。將其設置爲true當你第一次安裝並打開該應用,你可以將此代碼添加到您的func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool方法:

let defaults = UserDefaults.standard 

if (!defaults.dictionaryRepresentation().keys.contains("firstAccessToApp")) { 
    defaults.set(true, forKey: "firstAccessToApp") 
    defaults.synchronize() 
} 
+1

它的工作原理,謝謝! –