I have a an app in production I'm trying to convert from Swift 2.2 to Swift 3. I have tried the Swift 3 code in both XCode 8.1 and XCode 8.2.
The following Swift 2 code works perfectly:
func saveItemsToCache() {
NSKeyedArchiver.archiveRootObject(items, toFile: itemsCachePath)
}
func loadItemsFromCache() {
if let cachedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(itemsCachePath) as? [TruckItem] {
items = cachedItems
}
}
var itemsCachePath: String {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent("Trucks.dat")
return fileURL.path!
}
But the data isn't being persisted when I use the same code converted for Swift 3:
func saveItemsToCache() {
print("SAVED TRUCKS:", items)
NSKeyedArchiver.archiveRootObject(items, toFile: itemsCachePath)
}
func loadItemsFromCache() {
if let cachedItems = NSKeyedUnarchiver.unarchiveObject(withFile: itemsCachePath) as? [TruckItem] {
items = cachedItems
print("LOADED TRUCKS:", items)
}
}
var itemsCachePath: String {
let documentsURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("Trucks.dat")
return fileURL.path
}
Example console output:
SAVED TRUCKS: [<TruckTelematics.TruckItem: 0xc852380>, <TruckTelematics.TruckItem: 0x9b23ba0>]
LOADED TRUCKS: []