Reputation: 6581
I am trying to archive a dictionary using the following code and getting error. Obviously there is something is wrong in the response dictionary I am passing but the trace doesn't tell anything. How do I nail down the root cause?
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: response, requiringSecureCoding: false)
} catch {
NSLog("Unable to archive \(error)")
}
Error:
2019-07-17 19:08:38.978954+0530 MyApp-Swift[372:16845] Unable to archive Error Domain=NSCocoaErrorDomain Code=4866 "Caught exception during archival: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x282995e00 ( 0 CoreFoundation 0x00000001ca149ebc + 252 1 libobjc.A.dylib 0x00000001c9319a50 objc_exception_throw + 56 2 CoreFoundation 0x00000001ca062b14 + 0 3 CoreFoundation 0x00000001ca14f7bc + 1412 4 CoreFoundation 0x00000001ca15146c _CF_forwarding_prep_0 + 92 5 Foundation 0x00000001cabc4aa8 + 1276 6 Foundation 0x00000001caadc3b4 + 444 7 Foundation 0x00000001cab08ed8 + 964 8 Foundation 0x00000001cabc4aa8 + 1276 9 Foundation 0x00000001caadc3b4 + 444 10 Foundation 0x0000000
Upvotes: 2
Views: 2906
Reputation: 71
Just complementing matt's answer, which is absolutely right.
In my case, I was using a Struct that conformed to Codable and, to make it work, I just encoded it to a Dictionary [String: Any].
Applying it to your code, it would be something like this:
do {
let encodedResponse = (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(response))) as? [String: Any] ?? [:]
let data = try NSKeyedArchiver.archivedData(withRootObject: encodedResponse, requiringSecureCoding: false)
} catch {
NSLog("Unable to archive \(error)")
}
Upvotes: 1
Reputation: 535945
NSKeyedArchiver is for Cocoa Objective C objects only. Only NSCoding adopters can be archived with an NSKeyedArchiver. You would need an NSDictionary containing only NSCoding types. Well, you don’t have one.
Upvotes: 4