I have a textView which is the whole screen of the app. The users input new text, change the properties etc. I want the app save textview content with its properties for next times. I came up with userDefaults. I tried much but nothing happens. I couldn't find a solution to this. I tried this solution from stackoverflow https://stackoverflow.com/a/36940864/12698480 but no change. Again empty screen comes on the textview. My code as an extension to Userdefaults is as below:
//Save text
func setNSMutableText(string: NSMutableAttributedString?, forKey key: String){
var stringData: NSData?
if let string = string {
do {
stringData = try NSKeyedArchiver.archivedData(withRootObject: string, requiringSecureCoding: false) as NSData?
set(stringData, forKey: key)
print("archived NSMutableData")
} catch let err {
print("error archiving string data", err)
}
}
}
//LOAD text
func getNSMutableForKey(key: String) -> NSMutableAttributedString? {
var string: NSMutableAttributedString?
if let stringData = data(forKey: "screentextKey") {
do {
string = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSMutableAttributedString.self, from: stringData)
print("UNARchived string data!!!")
} catch let err {
print("error extracting string data", err)
}
}
return string
}
Usage:
//For saving
UserDefaults.standard.setNSMutableText(string: NSMutableAttributedString(attributedString: myTextView.attributedText), forKey: "screentextKey")
//For loading
override func viewDidLoad() {
super.viewDidLoad()
let oldstring = (UserDefaults.standard.getNSMutableForKey(key: "screentextKey"))!
myTextView.attributedText = oldstring
}
What is the problem? I saw that someone's suggestion about using NSAttributedString at the place of NSMutableAttributedString. I tried that way also, but no change.