我有一个功能,每次有人第一次打开我的项目时,我只想运行一次。如何修复我的代码,使其仅运行一次我的函数,每隔一次将值设置为false。任何解释都会非常有用。
// seedToDataBase()
var seed = seedToDataBase()
orderMyAnime()
do{
let firstRun = UserDefaults.standard.bool(forKey: seed) as Bool
if !firstRun {
//run your function
seedToDataBase()
UserDefaults.standard.set(true, forKey: seed)
}
}catch {
print("Unexpected error: \(error).")
}
这是我正在调用的函数:
func seedToDataBase()
{
var seedAnime: AnimeObjectMO!
for o in managedAnime{
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
seedAnime = AnimeObjectMO(context: appDelegate.persistentContainer.viewContext)
seedAnime.aName = o.aName
seedAnime.aRating = o.aRating
seedAnime.aRanking = o.aRanking
seedAnime.aDescription = o.aDescription
//newAnime.aImage = NSData(data: UIImageJPEGRepresentation(UIImage(named: addAnimeImage.text!)!, 1.0)!) as Data!
seedAnime.aImage = NSData(data: UIImagePNGRepresentation(o.aImage)!) as Data!
appDelegate.saveContext()
}
}
}
答案 0 :(得分:0)
try this code when you open the app that time you return false value in userdefault than after call the function
let hasLaunchedKey = "CallFunction"
let defaults = UserDefaults.standard
var hasLaunched = defaults.bool(forKey: hasLaunchedKey)
if !hasLaunched {
defaults.set(true, forKey: hasLaunchedKey)
}
func seedToDataBase()
{
var seedAnime: AnimeObjectMO!
for o in managedAnime{
if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
seedAnime = AnimeObjectMO(context: appDelegate.persistentContainer.viewContext)
seedAnime.aName = o.aName
seedAnime.aRating = o.aRating
seedAnime.aRanking = o.aRanking
seedAnime.aDescription = o.aDescription
//newAnime.aImage = NSData(data: UIImageJPEGRepresentation(UIImage(named: addAnimeImage.text!)!, 1.0)!) as Data!
seedAnime.aImage = NSData(data: UIImagePNGRepresentation(o.aImage)!) as Data!
appDelegate.saveContext()
}
}
}
答案 1 :(得分:0)
您的代码几乎正确,只是key
部分错误。
您的var seed = seedToDataBase()
每次调用时都会生成一个新实例。所以种子不是恒定的,每次都不同,这就是你的代码不起作用的原因。
UserDefault
的密钥应该是唯一的,因此您应该编写一些不会更改的String
名称,并且不应该将该名称用于其他UserDefault
操作。
将您的代码更改为:
// seedToDataBase()
var seed = seedToDataBase()
orderMyAnime()
do{
let firstRun = UserDefaults.standard.bool(forKey: "SomeKeyName")
if !firstRun {
//run your function
seedToDataBase()
UserDefaults.standard.set(true, forKey: "SomeKeyName")
}
}catch {
print("Unexpected error: \(error).")
}
答案 2 :(得分:0)
let hasRunAppOnceKey = "hasRunAppOnceKey"
let defaults = UserDefaults.standard
if defaults.bool(forKey: hasRunAppOnceKey) == false {
// Some code you want to run on first use...
defaults.set(true, forKey: hasRunAppOnceKey)
} else {
// Some code you want to run on every other time...
}