I am using userdefaults to save data in defaults and now I want to save/transfer that userdefaults data in one text file. Is it possible and if "yes" then how?
Thank you for help and appreciation.
I am using userdefaults to save data in defaults and now I want to save/transfer that userdefaults data in one text file. Is it possible and if "yes" then how?
Thank you for help and appreciation.
It would work like this example below. You can test it in the Playground:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let PersonKey = "PersonKey"
let textFileName = "textFile.txt"
UserDefaults.standard.removeObject(forKey: PersonKey)
class Person: NSObject, NSCoding {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.age = decoder.decodeInteger(forKey: "age")
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(age, forKey: "age")
}
func saveToFile() {
let content = "\(name) \(age)"
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/" + textFileName
do {
try content.write(toFile: fileName, atomically: true, encoding: .utf8)
} catch {
print(error)
}
}
static func loadDataFromFile() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/" + textFileName
let content: String
do{
content = try String(contentsOfFile: fileName, encoding: .utf8)
}catch _{
content = ""
}
return content;
}
}
let person = Person(name: "Bob", age: 33)
let ud = UserDefaults.standard
if ud.object(forKey: PersonKey) == nil {
print("Missing person in UD")
}
let encodedData = NSKeyedArchiver.archivedData(withRootObject: person)
ud.set(encodedData, forKey: PersonKey)
if let data = ud.data(forKey: PersonKey) {
print("Person data exist")
let unarchivedPerson = NSKeyedUnarchiver.unarchiveObject(with: data) as? Person
unarchivedPerson?.saveToFile()
}
let t = DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
print("Data from file: ", Person.loadDataFromFile())
})