我正在使用 userdefaults 在默认设置中保存数据,现在我想要保存/传输用户默认数据在一个文本文件中。是否可能,如果" 是"然后如何?
感谢您的帮助和赞赏。
答案 0 :(得分:0)
它会像下面这个例子一样工作。你可以在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())
})