Unable to get the string value stored in UserDefaults
var videoString = String()
In view did load
videoString = "http://site4brandz.com/cphp/26/uploads/oggy.mp4"
UserDefaults.standard.set(videoString as String, forKey: CurrentURL)
UserDefaults.standard.synchronize()
print("\(UserDefaults.standard.object(forKey: CurrentURL))")
It's printing as follows:
Optional(http://site4brandz.com/cphp/26/uploads/oggy.mp4)
When I go back and checking the same string like
if (UserDefaults.standard.value(forKey: CurrentURL) != nil) {
print("\(UserDefaults.standard.value(forKey: CurrentURL))")
let runningSrtring = UserDefaults.standard.value(forKey: CurrentURL)!
}
But now it's printing as Optional(4.067826)
where did I made a mistake?
To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.
There is no specific number attached to “a small amount”, but everything you store in UserDefaults will automatically be loaded when your app launches – if you store a lot in there your app launch will slow down. To give you at least an idea, you should aim to store no more than 512KB in there.
NSUserDefaults automatically persists the dictionary to a file every once in a while. The only reason there is a synchronize method is so your app can tell NSUserDefaults to persist the dictionary "now" instead of waiting for the automatic saving that will eventually happen.
Let's take a look at an example. We access the shared defaults object through the standard class property of the UserDefaults class. We then create an array of strings and store the array in the user's defaults database by invoking the set(_:forKey:) method of the UserDefaults database.
In Swift3
How about use UserDefaults.standard.string(forKey: CurrentURL)!
instead UserDefaults.standard.value(forKey: CurrentURL)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With