Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get String value from UserDefaults

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?

like image 423
Mahesh Narla Avatar asked Feb 03 '17 10:02

Mahesh Narla


People also ask

How to Store string in UserDefaults in swift?

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.

How much data can you store in UserDefaults?

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.

What is UserDefaults standard synchronize ()?

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.

How do you save an array of objects in UserDefaults?

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.


1 Answers

In Swift3

How about use UserDefaults.standard.string(forKey: CurrentURL)!

instead UserDefaults.standard.value(forKey: CurrentURL)!

like image 144
Cruz Avatar answered Sep 28 '22 14:09

Cruz