问题
When I say not running in the background, I mean when the user double clicked their home button and swipes up, the button will reenable
This is the code in my viewDidLoad
if let waitingDate:Date = UserDefaults.standard.value(forKey: "waitingDate") as? Date
{
let currentDate = Date()
if(currentDate.compare(waitingDate) == ComparisonResult.orderedDescending)
{
getPointsOutlet.isEnabled = true
}
}
This is the code in the @IBAction func
getPointsOutlet.isEnabled = false
let newDate = Calendar.current.date(byAdding: .day, value: 1, to: Date())
UserDefaults.standard.setValue(newDate, forKey: "waitingDate")
回答1:
To get the value always check use guard or if let statement to prevent the crash:-
//Set value in user default
UserDefaults.standard.set(Date(), forKey:"date")
UserDefaults.standard.synchronize()
//Get value from user default
guard let value = UserDefaults.standard.object(forKey: "date") as? Date else {return}
print(value)
回答2:
Save:
UserDefaults.standard.set(Date(), forKey:"date")
UserDefaults.standard.synchronize()
Retrieve:
if let dateValue = clickdate.object(forKey: "date") as? Date{
...
}
For enabling the button after 24 hours check this post: Enabling button after 24 hours
If you want to disable the button for 24 hours then save tomorrow's date:
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())
UserDefaults.standard.set(tomorrow, forKey:"date")
Checking if the button should be enabled:
let currentDate = Date()
if(currentDate.compare(dateValue) == ComparisonResult.orderedDescending){
//reenable button
}
来源:https://stackoverflow.com/questions/45374975/how-to-disable-a-button-even-when-it-is-not-running-in-the-background-in-swift