i get the error message above when retrieving UserDefaults. I saved the value as a String. TimeInterval is converted to String. Where is the problem?
Code for saving the string:
let timeResponse:TimeInterval = NSDate.timeIntervalSinceReferenceDate - start
let JSONTransferTime = TimeInterval.toReadableString(timeResponse) //converting to String
UserDefaults.standard.set(JSONTransferTime, forKey:"JSONTranferTime")
Code for retrieving the string:
let JSONTransferTime: String = UserDefaults.standard.string(forKey: "JSONTranferTime")! as String
Utils.displayAlert(title: "JSON download time", message: JSONTransferTime)
Exact error message:
[User Defaults] Attempt to set a non-property-list object (Function) as an NSUserDefaults/CFPreferences value for key JSONTranferTime
Code for toReadableString:
extension TimeInterval {
func toReadableString() -> String {
// Nanoseconds
let ns = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000000) % 1000
// Microseconds
let us = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000) % 1000
// Milliseconds
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
// Seconds
let s = Int(self) % 60
// Minutes
let mn = (Int(self) / 60) % 60
// Hours
let hr = (Int(self) / 3600)
var readableStr = ""
if hr != 0 {
readableStr += String(format: "%0.2dhr ", hr)
}
if mn != 0 {
readableStr += String(format: "%0.2dmn ", mn)
}
if s != 0 {
readableStr += String(format: "%0.2ds ", s)
}
if ms != 0 {
readableStr += String(format: "%0.3dms ", ms)
}
if us != 0 {
readableStr += String(format: "%0.3dus ", us)
}
if ns != 0 {
readableStr += String(format: "%0.3dns", ns)
}
return readableStr
}
}
JSONTransferTime-variable is filled:
toReadableString()
is an instance method, you have to call it on timeResponse
rather than on the type which returns the function the compiler is complaining about by the way.
let jsonTransferTime = timeResponse.toReadableString()
Please conform to the naming convention that variable names start with a lowercase letter and don't annotate types the compiler can infer.