How to save a CapturedRoom using NSCoder - swift

I'm trying to build an app that creates a floor plan of a room. I used ARWorldMap with ARPlaneAnchors for this but I recently discovered the Beta version of the RoomPlan API, which seems to lead to far better results.
However, I used te be able to just save an ARWorldMap using the NSCoding protocol, but this throws an error when I try to encode a CapturedRoom object:
-[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x141c18110
My code for encoding the class containing the CapturedRoom:
import RoomPlan
class RoomPlanScan: NSObject, NSCoding {
var capturedRoom: CapturedRoom
var title: String
var notes: String
init(capturedRoom: CapturedRoom, title: String, notes: String) {
self.capturedRoom = capturedRoom
self.title = title
self.notes = notes
}
required convenience init?(coder: NSCoder) {
guard let capturedRoom = coder.decodeObject(forKey: "capturedRoom") as? CapturedRoom,
let title = coder.decodeObject(forKey: "title") as? String,
let notes = coder.decodeObject(forKey: "notes") as? String
else { return nil }
self.init(
capturedRoom: capturedRoom,
title: title,
notes: notes
)
}
func encode(with coder: NSCoder) {
coder.encode(capturedRoom, forKey: "capturedRoom")
coder.encode(title, forKey: "title")
coder.encode(notes, forKey: "notes")
}
}
To be clear, the following code does work:
import RoomPlan
class RoomPlanScan: NSObject, NSCoding {
var worldMap: ARWorldMap
var title: String
var notes: String
init(worldMap: ARWorldMap, title: String, notes: String) {
self.worldMap = worldMap
self.title = title
self.notes = notes
}
required convenience init?(coder: NSCoder) {
guard let capturedRoom = coder.decodeObject(forKey: "worldMap") as? ARWorldMap,
let title = coder.decodeObject(forKey: "title") as? String,
let notes = coder.decodeObject(forKey: "notes") as? String
else { return nil }
self.init(
worldMap: worldMap,
title: title,
notes: notes
)
}
func encode(with coder: NSCoder) {
coder.encode(worldMap, forKey: "worldMap")
coder.encode(title, forKey: "title")
coder.encode(notes, forKey: "notes")
}
}
I'm writing the object to a local file using NSKeyedArchiver so it would be nice if I could keep the same structure using NSCoder. How can I fix this and save a CapturedRoom?

The issue is about saving CaptureRoom. According to the doc, it's not NS(Secure)Coding compliant, but it conforms to Decodable, Encodable, and Sendable
So you can use an Encoder/Decoder, to do CaptureRoom <-> Data, you could use the bridge NSData/Data, since NSData is NS(Secure)Coding compliant.
So, it could be something like the following code. I'll use JSONEncoder/JSONDecoder as partial Encoder/Decoder because they are quite common.
Encoding:
let capturedRoomData = try! JSONEncoder().encode(capturedRoom) as NSData
coder.encode(capturedRoomData, forKey: "capturedRoom")
Decoding:
let captureRoomData = coder.decodeObject(forKey: "capturedRoom") as! Data
let captureRoom = try! JSONDecoder().decode(CaptureRoom.self, data: captureRoomData)
Side note:
I used force unwrap (use of !) to simplify the code logic, but of course, you can use do/try/catch, guard let, if let, etc.)

Related

How to unarchive object using NSKeyedUnarchiver?

**I'm using this class: **
class Person: NSObject, NSCoding {
var name: String
var image: String
init(name: String, image: String) {
self.name = name
self.image = image
}
required init(coder aDecoder: NSCoder){
name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
image = aDecoder.decodeObject(forKey: "image") as? String ?? ""
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(image, forKey: "image")
}
}
For archiving, i used this method:
if let savedData = try? NSKeyedArchiver.archivedData(withRootObject: people, requireSecureCoding: false)
whrere people is Person class array [Person]
As for unarchiving, this method:
NSKeyedUnarchiver.unarchivedTopLevelObjectWithData()
is deprecated... which method should i use now ?
You now must tell the system what type you expect rather than simply unarchiving whatever is found:
try NSKeyedUnarchiver.unarchivedArrayOfObjects(ofClass: Person.self, from: savedData)

How do you save a custom class as an attribute of a CoreData entity in Swift 3?

I have a CoreData Entity SavedWorkout. It has the following attributes:
completionCounter is an array of Bool, and workout is a custom class called Workout.
I am saving my data like so:
let saveCompletionCounter = currentCompletionCounter
let saveDate = Date() as NSDate
let saveRoutineIndex = Int16(currentWorkoutRoutine)
let saveWorkout = NSKeyedArchiver.archivedData(withRootObject: workout)
item.setValue(saveDate, forKey: "date")
item.setValue(saveWorkout, forKey: "workout")
item.setValue(saveRoutineIndex, forKey: "routineIndex")
item.setValue(saveCompletionCounter, forKey: "completionCounter")
do {
try moc.save()
print("save successful")
} catch {
print("saving error")
}
where moc is an instance of NSManagedObjectContext, and item is an instance of NSManagedObject:
moc = appDelegate.managedObjectContext
entity = NSEntityDescription.entity(forEntityName: "SavedWorkout", in: moc)!
item = NSManagedObject(entity: entity, insertInto: moc)
In accordance with this and this and this , I have made my Workout class conform to NSObject and NSCoding, so it now looks like this:
class Workout: NSObject, NSCoding {
let name: String
let imageName: String
let routine: [WorkoutRoutine]
let shortDescription: String
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
imageName = aDecoder.decodeObject(forKey: "imageName") as! String
routine = aDecoder.decodeObject(forKey: "routine") as! [WorkoutRoutine]
shortDescription = aDecoder.decodeObject(forKey: "shortDescription") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(imageName, forKey: "imageName")
aCoder.encode(routine, forKey: "routine")
aCoder.encode(shortDescription, forKey: "shortDescription")
}
init(name: String, imageName: String, routine: [WorkoutRoutine], shortDescription: String) {
self.name = name
self.imageName = imageName
self.routine = routine
self.shortDescription = shortDescription
}
}
However I always get an error on the line routine: aDecoder.decodeObject....
The error says:
NSForwarding: warning: object 0x60800002cbe0 of class 'App.WorkoutRoutine' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[FitLift.WorkoutRoutine replacementObjectForKeyedArchiver:]
Why does this give me an error and not the other Transformable attribute? How do I save a custom class as a property of a CoreData entity?
The issue is that WorkoutRoutine is itself a custom class and as of your error it is not NSCoding compliant, therefore aCoder.encode(routine, forKey: "routine") doesn't really know how to encode it, as well as routine = aDecoder.decodeObject(forKey: "routine") as! [WorkoutRoutine] doesn't know how to decode it.
Not really related, but please try a safer approach for your coder and encoder initializer as the force unwrap might cause crashes if the encoder does not contain the keys you are looking for (for any reason)
required init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String,
let imageName = aDecoder.decodeObject(forKey: "imageName") as? String,
let routine = aDecoder.decodeObject(forKey: "routine") as? [WorkoutRoutine],
let shortDescription = aDecoder.decodeObject(forKey: "shortDescription") as? String else {
return nil
}
self.name = name
self.imageName = imageName
self.routine = routine
self.shortDescription = shortDescription
}

Swift 3 optional parameters

Is it possible to create optional initialization parameters in Swift so I can create an object from JSON with the values returned from the API call, but then when I'm saving that object later I can also save the downloaded UIImage for one of the urls I got before.
Example:
class Story: NSObject, NSCoding {
var id: Int?
var title, coverImageURL: String?
var coverImage: UIImage?
required init?(anId: Int?, aTitle: String?, aCoverImageURL: String?) {
self.id = anId
self.title = aTitle
self.coverImageURL = aCoverImageURL
}
convenience init?(json: [String: Any]) {
let id = json["id"] as? Int
let title = json["title"] as? String
let coverImageURL = json["cover_image"] as? String
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
)
}
Then Later I want to save objects to memory
//MARK: Types
struct PropertyKey {
static let id = "id"
static let title = "title"
static let coverImageURL = "coverImageURL"
static let coverImage = "coverImage"
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: PropertyKey.id)
aCoder.encode(title, forKey: PropertyKey.title)
aCoder.encode(coverImageURL, forKey: PropertyKey.coverImageURL)
aCoder.encode(coverImage, forKey: PropertyKey.coverImage)
}
required convenience init?(coder aDecoder: NSCoder) {
guard let id = aDecoder.decodeObject(forKey: PropertyKey.id) as? Int else {
os_log("Unable to decode the id for a Story object.", log: OSLog.default, type: .debug)
return nil
}
guard let title = aDecoder.decodeObject(forKey: PropertyKey.title) as? String else {
os_log("Unable to decode the title for a Story object.", log: OSLog.default, type: .debug)
return nil
}
let coverImageURL = aDecoder.decodeObject(forKey: PropertyKey.coverImageURL) as? String
let coverImage = aDecoder.decodeObject(forKey: PropertyKey.coverImage) as? UIImage
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
coverImage: coverImage,
)
}
Does this make sense? I want to be able to save a Story object as soon as I get the response from the API, but later when I save the story to memory, I want to be able to save the fetched UIImage for the coverImage.
How would I do that?
I'm not sure why no one took the easy points on this answer, but the answer is to simply make your properties optionals, and then you can set them with a value, or nil. You can also create convenience initializers that automatically set certain values to nil if you want. So, using my app as an example, I have a model that gets built from an API call. that model has values like id, created_at, etc that don't exist until a record is saved to the server, but I create objects locally, store them, and eventually send them to the server, so I need to be able to set the above values only when creating an object from JSON, so here is what I did:
class Story: NSObject, NSCoding {
var id: Int?
var title, coverImageURL: String?
var coverImage: UIImage?
required init?(anId: Int?, aTitle: String?, aCoverImageURL: String?) {
self.id = anId
self.title = aTitle
self.coverImageURL = aCoverImageURL
}
convenience init?(json: [String: Any]) {
let id = json["id"] as? Int
let title = json["title"] as? String
let coverImageURL = json["cover_image"] as? String
self.init(
anId: id,
aTitle: title,
aCoverImageURL: coverImageURL,
)
}
convenience init?(aTitle: String, aCoverImage: UIImage?) {
let title = aTitle
let subtitle = aSubtitle
let coverImage = aCoverImage
let isActive = activeStatus
self.init(
anId: nil,
aTitle: title,
aCoverImageURL: nil,
aCoverImage: coverImage,
)
}
As you can see, I only set two of the values when I'm creating an object locally, and the other values are just set to nil. To allow a value to be set to nil, just make it an optional when setting it. Simple!

Swift3: [String: AnyObject] using NSCoding protocol to save with NSUserDefaults

I have my custom class:
private class PendingRequest : NSObject, NSCoding
{
var route : String!
var params: [String: AnyObject]!
init(route: String, params: [String: AnyObject])
{
self.route = route
self.params = params
}
required init(coder aDecoder: NSCoder)
{
self.route = aDecoder.decodeObject(forKey: "route") as! String
self.params = aDecoder.decodeObject(forKey: "params") as! [String: AnyObject]
}
public func encode(with coder: NSCoder)
{
coder.encode(route, forKey: "route")
coder.encode(params, forKey: "params")
}
}
And here is how I save my list of PendingRequest:
private static func savePendingRequests(requestsToSend: [PendingRequest])
{
let data = NSKeyedArchiver.archivedData(withRootObject: requestsToSend!)
UserDefaults.standard.set(data, forKey: self.requestsToSendDefaultsString)
}
And here is how I try to retrieve it:
let data = UserDefaults.standard.data(forKey: requestsToSendDefaultsString)
let requests = NSKeyedUnarchiver.unarchiveObject(with: data!) as! [PendingRequest]
return requests
But my code crashes when retrieving my data... Saving works fine, but not retrieving... Any idea?
EDIT: Here is my Crashlytics error:
*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (_TtCC6Versus9VersusAPIP33_8D2B8AA415FDC4F8DFAF29D7ECE33C1F14PendingRequest) for key (NS.objects); the class may be defined in source code or a library that is not linked
SOLUTION:
My class PendingRequest was fileprivate, thus NSKeyedUnarchiver couldn't access it, hence the crash... Thanks for your help.
Few things are incorrect
you're forgetting to call super.init() in your initializers
init(route: String, params: [String: AnyObject])
{
self.route = route
self.params = params
super.init()
}
required init(coder aDecoder: NSCoder)
{
self.route = aDecoder.decodeObject(forKey: "route") as? String
self.params = aDecoder.decodeObject(forKey: "params") as? [String: AnyObject]
// Check if route and params are what you expected here
super.init()
}
You have a static method that calls "self", I'm not sure this works, you could still have a static key or a global key.
Plus you're unwrapping a non-optional value "requestsToSend".
I think this would solve it.
private static func savePendingRequests(requestsToSend:[PendingRequest])
{
let data = NSKeyedArchiver.archivedData(withRootObject: requestsToSend)
UserDefaults.standard.set(data, forKey: "AStaticKey")
}
Then retrieving should work. (I added a few safety checks)
guard let data = UserDefaults.standard.data(forKey: "AStaticKey"),
let requests = NSKeyedUnarchiver.unarchiveObject(with: data) as? [PendingRequest] else {
return [PendingRequest]()
}
return requests

Swift objects array to plist file

I am trying to save my object's array to array.plist but I get the following error:
Thread 1: signal SIGABRT error
My object class looks like this:
class Note {
// MARK: Properties
var title: String
var photo: UIImage?
var text: String
// MARK: Initialization
init?(title: String, photo: UIImage?, text: String) {
// Initialize stored properties.
self.title = title
self.photo = photo
self.text = text
// Initialization should fail if there is no name or if the rating is negative.
if title.isEmpty{
return nil
}
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(title, forKey:"title")
aCoder.encodeObject(text, forKey:"text")
aCoder.encodeObject(photo, forKey:"photo")
}
init (coder aDecoder: NSCoder!) {
self.title = aDecoder.decodeObjectForKey("title") as! String
self.text = aDecoder.decodeObjectForKey("text") as! String
self.photo = aDecoder.decodeObjectForKey("photo") as! UIImage
}
}
In the controller, I try to save the array with the Notes object like this:
notes = [Notes]()
notes.append(note)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true)
let path: AnyObject = paths[0]
let arrPath = path.stringByAppendingString("/array.plist")
NSKeyedArchiver.archiveRootObject(notes, toFile: arrPath)
Not all the properties in your class are not optional, yet when you retrieve them from the plist, you are unwrapping all of them. This might cause your code to crash.
For example, if the photo is nil and you saved the object, when you are retrieving it, you are unwrapping it self.photo = aDecoder.decodeObjectForKey("photo") as! UIImage, which will crash if you did not save anything there.
Try removing the unwrapping and check again for your crash. Even if this was not the cause of your crash, it will cause a crash at some point.
If this does not fix your problem, please paste the complete error log so it is a bit more clear what is happening.
For swift 5. You can save an array of custom classes to a .plist file that inherits from NSObject and NSSecureCoding.
If we create a custom class called Person:
import Foundation
class Person: NSObject, NSSecureCoding {
//Must conform to NSSecureCoding protocol
public class var supportsSecureCoding: Bool { return true } //set to 'true'
//just some generic things to describe a person
private var name:String!
private var gender:String!
private var height:Double!
//used to create a new instance of the class 'Person'
init(name:String, gender:String, height:Double) {
super.init()
self.name = name
self.gender = gender
self.height = height
}
//used for NSSecureCoding:
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name") //encodes the name to a key of 'name'
coder.encode(gender, forKey: "gender")
coder.encode(height, forKey: "height")
}
//used for NSSecureCoding:
required init?(coder: NSCoder) {
super.init()
self.name = (coder.decodeObject(forKey: "name") as! String)
self.gender = (coder.decodeObject(forKey: "gender") as! String)
self.height = (coder.decodeObject(forKey: "height") as! Double)
}
//created just to print the data from the class
public override var description: String { return String(format: "name=%#,gender=%#,height%f", name, gender, height) }
}
Now we can create functions to save and load from a .plist file in the ViewController class:
We need to gather data from the directory system of the device:
func documentsDirectory()->String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths.first!
return documentsDirectory
}
func dataFilePath ()->String{
return self.documentsDirectory().appendingFormat("/your_file_name_here.plist")
}
function to save the array:
func saveData(_ people:[Person]) {
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
archiver.encode(people, forKey: "your_file_name_here")
let data = archiver.encodedData
try! data.write(to: URL(fileURLWithPath: dataFilePath()))
}
function to load the array:
func loadData() -> [Person] {
let path = self.dataFilePath()
let defaultManager = FileManager()
var arr = [Person]()
if defaultManager.fileExists(atPath: path) {
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: data)
//Ensure the unarchiver is required to use secure coding
unarchiver.requiresSecureCoding = true
//This is where it is important to specify classes that can be decoded:
unarchiver.setClass(Person.classForCoder(), forClassName: "parentModule.Person")
let allowedClasses =[NSArray.classForCoder(),Person.classForCoder()]
//Finally decode the object as an array of your custom class
arr = unarchiver.decodeObject(of: allowedClasses, forKey: "your_file_name_here") as! [Person]
unarchiver.finishDecoding()
}
return arr
}
In the ViewController class:
override func viewDidLoad() {
super.viewDidLoad()
let testPerson = Person(name: "Bill", gender: "Male", height: 65.5)
let people:[Person] = [testPerson]
//Save the array
saveData(people)
//Load and print the first index in the array
print(loadData()[0].description)
}
Output:
[name=Bill,gender=Male,height=65.5000000]