I'm a new at swift, please help. Try to archive and unarchive object and write/read it on disk.
I have a class FourLines
class FourLines: NSObject, NSCoding, NSSecureCoding, NSCopying {
static var supportsSecureCoding: Bool{
return true
}
private static let linesKey = "linesKey"
var lines: [String]?
override init() {
}
required init?(coder aDecoder: NSCoder) {
print("FourLines init")
lines = aDecoder.decodeObject(forKey: FourLines.linesKey) as? [String]
}
func encode(with aCoder: NSCoder) {
print("FourLines encode")
if let saveLines = lines {
aCoder.encode(saveLines, forKey: FourLines.linesKey)
}
}
func copy(with zone: NSZone? = nil) -> Any {
print("copy with zone")
let copy = FourLines()
if let linesToCopy = lines {
var newLines = Array<String>()
for line in linesToCopy {
newLines.append(line)
}
copy.lines = newLines
}
return copy
}
}
In ViewController i try to save and read data:
class ViewController: UIViewController {
private static let linesKey = "linesKey"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let fileURL = self.dataFileUrl()
if FileManager.default.fileExists(atPath: fileURL.path!) {
let codedData = try! Data(contentsOf: fileURL as URL)
print(codedData)
let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: codedData)
if unarchiver.containsValue(forKey: ViewController.linesKey) {
print("viewDidLoad contains value")
} else {
print("viewDidLoad doesn't conains value")
}
let fourLines = unarchiver.decodeObject(forKey: ViewController.linesKey) as! FourLines?
print(fourLines?.lines?.count)
}
let app = UIApplication.shared
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: app)
}
@objc func applicationWillResignActive(notification: NSNotification) {
print("applicationWillResignActive")
let fileURL = self.dataFileUrl()
print(fileURL)
let fourLines = FourLines()
let array = (self.lineFields as NSArray).value(forKey: "text") as! [String]
fourLines.lines = array
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
archiver.encode(fourLines, forKey: ViewController.linesKey)
let data = archiver.encodedData
do {
try data.write(to: fileURL as URL)
} catch {
print("Error is \(error)")
}
}
@IBOutlet var lineFields: [UITextField]!
func dataFileUrl() -> NSURL {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
var url: NSURL?
url = URL(fileURLWithPath: "") as NSURL
do {
try url = urls.first!.appendingPathComponent("data.archive") as NSURL
} catch {
print("Error is \(error)")
}
return url!
}
}
When I resign app encode method invokes: FourLines encode
And when I try to load it, I see file is created and it contains value, but I always have nil while decode fourLines object:
322 bytes viewDidLoad contains value nil
And init? coder aDecoder and copy with zone never invoke. What do I wrong?
NSCoding, useCodableandJSONEncoder/PropertyListEncoder. - Dávid Pásztor