0

I'm very new to coding in swift, so I barely know any of the syntaxes. I am defining a variable in view controller and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code

import UIKit
let stranger = String(arc4random_uniform(10000))

class ViewController: UIViewController {...}
2
  • Save the value into user defaults with unique key. access the value by giving unique key from user defaults. Commented Oct 4, 2017 at 9:26
  • userDefaults is a great way to store data easily in non volatile memory, but you might want to check keychain if the value you want to store is secret/private. UserDefaults is not secured and can easily be read. Commented Oct 4, 2017 at 9:52

2 Answers 2

3

You should use UserDefaults for save your random value. When you open you app first time then you will be got some random value in stranger. Add those value in UserDefaults with specific key and you can access value by use of key that you set in UserDefault.

Ex.

You get random value 1234 in stranger then you should first check you already set the value or not?

if UserDefaults.standard.object(forKey: "keyRandom") == nil { // If value already set then you do not need to reset
  UserDefaults.standard.set(stranger, forKey: "keyRandom")
}

And if you want to access value you can get it by

print("\(UserDefaults.standard.object(forKey: "keyRandom") ?? "not Found")")
Sign up to request clarification or add additional context in comments.

2 Comments

Don’t use value for key and don’t force unwrap. Your App will crash if that value hasn’t being set. Also UserDefaults has a specific method to retrieve a String from it called string(forKey:) among other types. It also has a method to register default values into it as shown in the answer below.
Don’t use setValue use set(Any:, forKey:) and again don’t use value(forKey:) use string(forKey:) or object(forKey:)
0

You need to store the data in a persistent data store if you want to persist between launches. UserDefaults is a simple solution, and you can use the registerDefaults method to seed it.

Register your default properties. In AppDelegate.didFinishingLaunching may be a good place

UserDefaults.standard.register(defaults: [
            "MyKey" : String(arc4random_uniform(10000))
        ])

Pull out the value:

let stranger = UserDefaults.standard.string(forKey: "MyKey")

If you don't want to register the defaults on app start, or need to change it, then you can also set the property when you first need it, using an if let check to see if it already exists, and if not, set it.

func getStranger() -> String {
    if let v = UserDefaults.standard.string(forKey: "MyKey") {
        return v
    } else {
        let rand = String(arc4random_uniform(10000))
        UserDefaults.standard.set(rand, forKey:"MyKey")
        return rand
    }
}

Note: Code written in SO answer box, not tested and may contain syntax errors. Demo purposes only

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.