简体   繁体   中英

How to use NSUserDefaults to check between current time and last posting time?

My idea is that when Button "A" is tapped every time, it will set the NSDate value automatically. When the current time is larger than the existing NSDate value, it print "yes". Here is my code but I dont know what's wrong. import UIKit

class ViewController: UIViewController {

var currentDateTime = NSDate()

override func viewDidLoad() {


    super.viewDidLoad()

    observeTime()
    }

@IBAction func show(_ sender: Any) {
    print(UserDefaults.standard.dictionaryRepresentation())

}
let userDefaults = UserDefaults.standard

func observeTime() {
    let posttime = userDefaults.object(forKey: "LastPostingTime") as? NSDate

    if ((posttime?.isGreaterThanDate(dateToCompare: currentDateTime))!) {
        print("yes")
    }
}


@IBAction func hihi(_ sender: Any) {


    observeTime()
            userDefaults.set(NSDate(), forKey: "LastPostingTime")


}



}

extension NSDate {
func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isGreater = false

    //Compare Values
    if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending {
        isGreater = true
    }

    //Return Result
    return isGreater
}

}

In function hihi you first store the current date into NSUserDefaults before reading it. So you will get back what you just stored: the current time.

You may want to read it first, compare it to currentDateTime and then store it into user defaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM