0

In my app I am we are sending TimeStamp along with parameters for API calls to get data from. I could use any random string to pass with the values but I am using TimeStamp because it will be different everytime so that I will get fresh data everytime without cashing. Now our requirement is to update TimeStamp every hour so that everytime when I make an API call instead of showing fresh data everytime, data will be updated every hour.

My API looks like this:

let url = "https://myurl.api.getthisapidata?id=\(someID)&nocache=\(timeStamp)"

Now in the place of TimeStamp I want to send some random string like "\(arc4random())". But I want this random string to be changed only after an hour so that I go to some other view or closes the app and opens it before an hour this random string should remain same.

I hope you understand what I am trying to convey.

TimeStamp extenstion:

extension Date {
    var ticks: UInt64 {
        let timeStamp = UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)
        return timeStamp
    }
}

Usage:

print(Date().ticks)
  • I think you should still use `timeStamp` but this time you need to store it inside `Userdefaults` and check everytime if the time difference is more than an hour then send & store new timestamp otherwise use the saved one. – Kamran May 21 '19 at 06:40
  • 2
    What about sending `Int(timeStamp) / 3600`, which would be a different number every hour? – Sweeper May 21 '19 at 06:43
  • @Sweeper It is not working like that.. I will add the code of getting time stamp so that you can suggest on any changes. – Venkatesh Chejarla May 21 '19 at 06:59
  • @Kamran How to do that, I tried a few different ways using Timer class. But they didn't work. – Venkatesh Chejarla May 21 '19 at 07:01
  • 1
    Your “ticks” increments in 100 nanosecond intervals, compare https://stackoverflow.com/a/39830452/1187415. What @Sweeper is suggesting is something like `Int(Date().timeIntervalSince1970)/3600` which would increment every hour. – Martin R May 21 '19 at 07:29

1 Answers1

0

Get current hour value from current date using component(_:from:) method. Then append a random string with it.

class RandomStringGenerator: NSObject {
    static let shared = RandomStringGenerator()
    var oldString:String {
        get {
            return UserDefaults.standard.string(forKey: "oldString") ?? ""
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "oldString")
        }
    }
    func getString() -> String {
        let random = Int64.random(in: 10_000_00..<10_000_000)
        let hour = Calendar.current.component(.hour, from: Date())
        if !oldString.hasPrefix("\(hour)") {
            oldString = "\(hour)" + "\(random)"
        }
        return oldString
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70