custom class storage - cannot encode structs - swift

I am trying to store an array of a custom class using UserDefaults. The custom class is for annotations using a mixture of strings and CLLocationCoordinate2D.
I am calling ArchiveUtil.savePins(pins: pins) when I perform a long press gesture in the Map View.
However, I am getting an error
-[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs'
Any ideas what I am doing wrong?
Thanks, code below:
class PinLocation: NSObject, NSCoding, MKAnnotation {
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(name:String, description: String, lat:CLLocationDegrees,long:CLLocationDegrees){
title = name
subtitle = description
coordinate = CLLocationCoordinate2DMake(lat, long)
}
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObject(forKey: "title") as? String
subtitle = aDecoder.decodeObject(forKey: "subtitle") as? String
coordinate = aDecoder.decodeObject(forKey: "coordinate") as! CLLocationCoordinate2D
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(subtitle, forKey: "subtitle")
aCoder.encode(coordinate, forKey: "coordinate")
}
}
class ArchiveUtil {
private static let PinKey = "PinKey"
private static func archivePins(pin: [PinLocation]) -> NSData{
return NSKeyedArchiver.archivedData(withRootObject: pin as NSArray) as NSData
}
static func loadPins() -> [PinLocation]? {
if let unarchivedObject = UserDefaults.standard.object(forKey: PinKey) as? Data{
return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [PinLocation]
}
return nil
}
static func savePins(pins: [PinLocation]?){
let archivedObject = archivePins(pin: pins!)
UserDefaults.standard.set(archivedObject, forKey: PinKey)
UserDefaults.standard.synchronize()
}
}

The error is pretty clear: CLLocationCoordinate2D is a struct and this archiver cannot encode structs.
A simple workaround is to en- and decode latitude and longitude separately.
By the way, since both String properties are initialized with non-optional values declare them also as non-optional. If they are supposed not to be changed declare them even as constant (let)
var title: String
var subtitle: String
...
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObject(forKey: "title") as! String
subtitle = aDecoder.decodeObject(forKey: "subtitle") as! String
let latitude = aDecoder.decodeDouble(forKey: "latitude")
let longitude = aDecoder.decodeDouble(forKey: "longitude")
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "title")
aCoder.encode(subtitle, forKey: "subtitle")
aCoder.encode(coordinate.latitude, forKey: "latitude")
aCoder.encode(coordinate.longitude, forKey: "longitude")
}

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 to save a CapturedRoom using NSCoder

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.)

Swift Core Data Storing Custom Class return nil

I want to store Arrays with custom Objects to Core Data. I want to store two arrays with custom Classes. The first would be checkpoints as Array<[Checkpoint]> and the second one would be track as Array . Here's the Data Model: Data Model
import Foundation
import CoreData
public class Checkpoint: NSObject, NSCoding {
public static var supportsSecureCoding = true
public var longitude:Double?
public var latitude:Double?
public var instruction:String?
public var tts:Bool?
public var len_track:Int?
init(longitude: Double, latitude: Double, instruction: String, tts: Bool, len_track: Int) {
self.longitude = longitude
self.latitude = latitude
self.instruction = instruction
self.tts = tts
self.len_track = len_track
}
public func encode(with coder: NSCoder) {
coder.encode(longitude, forKey: "longitude")
coder.encode(latitude, forKey: "latitude")
coder.encode(instruction, forKey: "instruction")
coder.encode(tts, forKey: "tts")
coder.encode(len_track, forKey: "len_track")
}
public required init?(coder: NSCoder) {
guard let longitude = coder.decodeObject(forKey: "longitude") as? Double,
let latitude = coder.decodeObject(forKey: "latitude") as? Double,
let instruction = coder.decodeObject(forKey: "instruction") as? String,
let tts = coder.decodeObject(forKey: "tts") as? Bool,
let len_track = coder.decodeObject(forKey: "len_track") as? Int else {
return nil
}
self.longitude = longitude
self.latitude = latitude
self.instruction = instruction
self.tts = tts
self.len_track = len_track
}
}
public class Coordinates: NSObject, NSCoding {
public static var supportsSecureCoding = true
var latitude: Float?
var longitude: Float?
init(longitude: Float, latitude: Float) {
self.longitude = longitude
self.latitude = latitude
}
public func encode(with coder: NSCoder) {
coder.encode(longitude, forKey: "longitude")
coder.encode(latitude, forKey: "latitude")
}
public required init?(coder: NSCoder) {
guard let longitude = coder.decodeObject(forKey: "longitude") as? Float,
let latitude = coder.decodeObject(forKey: "latitude") as? Float else {
return nil
}
self.longitude = longitude
self.latitude = latitude
}
}
Apart from the two Transformable Entities, everything can be stored normally. But when I add checkpoints and track to a route, I get the following error:
Thread 1: "*** -decodeObjectForKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!"

Save and get details of Model class using userdefault

I have one model object User and inside that another model object is Picture.
"user": {
"id": 1,
"email": "abc.k#gmail.com",
"user_profile_photo": {
"id": 997,
"user_id": 1,
"photo_url": "https://newproduction.s3.amazonaws.com/profile_image/RkUJAczv5nWpUyFTgyTgMLChR.jpeg",
}
}
I have two model class for this one is User and another is Picture inside user.
I am saving model user in userdefault as below
//Get Response
loginResponseObj = Mapper<LoginResponse>().map(JSONObject:(response.result.value))
//Save user Details
let userData = loginResponseObj.user!
let data = NSKeyedArchiver.archivedData(withRootObject: userData)
UserDefaults.standard.set(data, forKey:"user")
and when i am trying to get data from userdefaults, am getting User Model but inside details are nil.
Get Userdetails from userdefault Code is below
guard let data = UserDefaults.standard.object(forKey: "user") as? Data
else
{
return UserModel()
}
return (NSKeyedUnarchiver.unarchiveObject(with: data) as? UserModel)!
This return **<ABC.User: 0x7f84f740c440>**
But when i am trying to get Picture from User it return nil
In User Model
class User:NSObject,Mappable,NSCoding{
var email: String?
var picture: Picture?
required init?(coder aDecoder: NSCoder) {
self.email = aDecoder.decodeObject(forKey: "email") as? String
}
func initWithCoder(aDecoder:NSCoder) -> UserModel
{
self.email = aDecoder.decodeObject(forKey: "email") as? String
return self
}
func encode(with aCoder: NSCoder) {
aCoder.encode(email, forKey: "email")
}
}
In Picture Model
class Picture:Mappable,NSCoding{
var id: String?
var photoURL: String?
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeObject(forKey: "id") as? String
self.photoURL = aDecoder.decodeObject(forKey: "photoURL") as? String
}
func initWithCoder(aDecoder:NSCoder) -> Picture
{
self.id = aDecoder.decodeObject(forKey: "id") as? String
self.photoURL = aDecoder.decodeObject(forKey: "photoURL") as? String
return self
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
}
}
Note: I am using MVVM Pattern and Object Mapper
So, How can i get the whole details of user including photo_url (User.Picture.photo_url) ?
In User Model
class User:NSObject,Mappable,NSCoding{
var email: String?
var picture: Picture?
required init?(coder aDecoder: NSCoder) {
self.email = aDecoder.decodeObject(forKey: "email") as? String
self.picture = aDecoder.decodeObject(forKey: "picture") as? Picture
}
func initWithCoder(aDecoder:NSCoder) -> UserModel
{
self.email = aDecoder.decodeObject(forKey: "email") as? String
self.picture = aDecoder.decodeObject(forKey: "picture") as? Picture
return self
}
func encode(with aCoder: NSCoder) {
aCoder.encode(email, forKey: "email")
aCoder.encode(picture, forKey: "picture")
}
}
In Picture Model
class Picture: NSObject,Mappable,NSCoding {
var id: String?
var photoURL: String?
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeObject(forKey: "id") as? String
self.photoURL = aDecoder.decodeObject(forKey: "photoURL") as? String
}
func initWithCoder(aDecoder:NSCoder) -> Picture
{
self.id = aDecoder.decodeObject(forKey: "id") as? String
self.photoURL = aDecoder.decodeObject(forKey: "photoURL") as? String
return self
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(photoURL, forKey: "photoURL")
}
Get Details From User Defaults
guard let data = UserDefaults.standard.object(forKey: "user") as? Data
else
{
return User()
}
return (NSKeyedUnarchiver.unarchiveObject(with: data) as? User)!
above code will return User Model
Using this model access its variables
print(user.email)
print(user.picture.photoURL)

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
}