UserDefaults is a built-in class in Swift that allows you to store and retrieve small amounts of user-related data. It provides a simple and convenient way to save user preferences, settings, and other application-specific data.
To work with UserDefaults in Swift, you need to follow these steps:
- Import the Foundation framework: Before you can use UserDefaults, you need to import the Foundation framework at the top of your Swift file.
1
|
import Foundation
|
- Save data to UserDefaults: To save data to UserDefaults, you can use the set(_:forKey:) method. The data types supported by UserDefaults include integers, floats, booleans, strings, arrays, dictionaries, and dates.
1 2 3 4 |
let defaults = UserDefaults.standard defaults.set(42, forKey: "MyNumber") defaults.set("John", forKey: "Username") defaults.set(true, forKey: "IsLoggedIn") |
- Retrieve data from UserDefaults: To retrieve data from UserDefaults, you can use the object(forKey:) method. Make sure to cast the retrieved value to the appropriate data type.
1 2 3 |
let number = defaults.object(forKey: "MyNumber") as? Int ?? 0 let username = defaults.object(forKey: "Username") as? String ?? "" let isLoggedIn = defaults.object(forKey: "IsLoggedIn") as? Bool ?? false |
- Remove data from UserDefaults: To remove data from UserDefaults, you can use the removeObject(forKey:) method.
1
|
defaults.removeObject(forKey: "Username")
|
- Synchronize changes: UserDefaults automatically saves changes to disk periodically. However, if you want to ensure that the changes are immediately saved, you can call the synchronize() method.
1
|
defaults.synchronize()
|
By using UserDefaults, you can easily save and retrieve user-related data in your Swift applications, making it convenient to handle user preferences and settings.
How to set a value in UserDefaults in Swift?
To set a value in UserDefaults in Swift, you can use the following steps:
- Import the UserDefaults module at the top of your file:
1
|
import UIKit
|
- Set the value using the set(_:forKey:) method of the UserDefaults class. For example, to set a string value for a key:
1 2 |
let defaults = UserDefaults.standard defaults.set("Hello, World!", forKey: "myKey") |
- Call the synchronize() method to save the changes immediately. Although this step is not necessary in modern versions of Swift, it ensures that the value is saved in older versions:
1
|
defaults.synchronize()
|
That's it! The value is now set in the UserDefaults. You can access it later using the same key.
How to retrieve a float value from UserDefaults in Swift?
To retrieve a float value from UserDefaults
in Swift, you can follow these steps:
- Access the UserDefaults instance using the standard property.
1
|
let defaults = UserDefaults.standard
|
- Use the float(forKey:) method of UserDefaults to retrieve the float value associated with a specific key. Provide the key you used when setting the value.
1
|
let floatValue = defaults.float(forKey: "yourFloatKey")
|
- If the specified key does not exist in UserDefaults, the float(forKey:) method will return 0.0 by default. You can check for the existence of the key using the object(forKey:) method and handle the case accordingly.
1 2 3 4 5 6 7 |
if defaults.object(forKey: "yourFloatKey") != nil { let floatValue = defaults.float(forKey: "yourFloatKey") // Handle the retrieved float value } else { // Key does not exist in UserDefaults } |
Make sure to replace "yourFloatKey"
with the actual key you used when storing the float value in UserDefaults
.
How to encrypt values stored in UserDefaults in Swift?
To encrypt values stored in UserDefaults in Swift, you can follow these steps:
- Define an Encryption/Decryption Key:
1
|
let encryptionKey = "YourEncryptionKey"
|
- Add an Encryption extension:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import Foundation import CommonCrypto extension String { func encrypt(key: String) throws -> String { guard let keyData = key.data(using: .utf8), let messageData = self.data(using: .utf8) else { throw NSError(domain: "EncryptionError", code: 0, userInfo: nil) } let cryptLength = messageData.count + kCCBlockSizeAES128 var cryptData = Data(count: cryptLength) let keyLength = size_t(kCCKeySizeAES128) let options = CCOptions(kCCOptionPKCS7Padding) var numBytesEncrypted: size_t = 0 let status = cryptData.withUnsafeMutableBytes { cryptBytes in keyData.withUnsafeBytes { keyBytes in messageData.withUnsafeBytes { dataBytes in CCCrypt(CCOperation(kCCEncrypt), UInt32(kCCAlgorithmAES128), options, keyBytes, keyLength, nil, dataBytes, messageData.count, cryptBytes, cryptLength, &numBytesEncrypted) } } } if status == CCCryptorStatus(kCCSuccess) { cryptData.count = numBytesEncrypted return cryptData.base64EncodedString() } else { throw NSError(domain: "EncryptionError", code: Int(status), userInfo: nil) } } func decrypt(key: String) throws -> String { guard let keyData = key.data(using: .utf8), let messageData = Data(base64Encoded: self) else { throw NSError(domain: "DecryptionError", code: 0, userInfo: nil) } let cryptLength = messageData.count + kCCBlockSizeAES128 var cryptData = Data(count: cryptLength) let keyLength = size_t(kCCKeySizeAES128) let options = CCOptions(kCCOptionPKCS7Padding) var numBytesDecrypted: size_t = 0 let status = cryptData.withUnsafeMutableBytes { cryptBytes in keyData.withUnsafeBytes { keyBytes in messageData.withUnsafeBytes { dataBytes in CCCrypt(CCOperation(kCCDecrypt), UInt32(kCCAlgorithmAES128), options, keyBytes, keyLength, nil, dataBytes, messageData.count, cryptBytes, cryptLength, &numBytesDecrypted) } } } if status == CCCryptorStatus(kCCSuccess) { cryptData.count = numBytesDecrypted return String(data: cryptData, encoding: .utf8) ?? "" } else { throw NSError(domain: "DecryptionError", code: Int(status), userInfo: nil) } } } |
- Encrypt and store the value in UserDefaults:
1 2 3 4 5 6 7 |
let valueToEncrypt = "Value to Encrypt" do { let encryptedValue = try valueToEncrypt.encrypt(key: encryptionKey) UserDefaults.standard.set(encryptedValue, forKey: "EncryptedValue") } catch { print("Encryption Error: \(error)") } |
- Decrypt the value from UserDefaults:
1 2 3 4 5 6 7 8 |
if let encryptedValue = UserDefaults.standard.string(forKey: "EncryptedValue") { do { let decryptedValue = try encryptedValue.decrypt(key: encryptionKey) print("Decrypted Value: \(decryptedValue)") } catch { print("Decryption Error: \(error)") } } |
Make sure to replace "YourEncryptionKey"
with your desired encryption key.
How to set a default value in UserDefaults in Swift?
To set a default value in UserDefaults in Swift, you can use the register(defaults:)
method of the UserDefaults
class. Here's an example:
1 2 3 4 5 |
// Get the standard UserDefaults instance let defaults = UserDefaults.standard // Set the default value for a specific key defaults.register(defaults: ["myKey": "defaultValue"]) |
In this example, the key "myKey" is set to a default value of "defaultValue". If this key has not been previously set by the user or programmatically, it will have the default value.
You can set multiple default values by providing a dictionary to the register(defaults:)
method. Each key-value pair in the dictionary represents a default value for a specific key.
Remember to call register(defaults:)
before accessing any values in the UserDefaults, preferably during app launch or in the application(_:didFinishLaunchingWithOptions:)
method in your AppDelegate file.