TheM4hd1 / SwiftyInsta

Instagram Private API Swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Attempting to archive [SwiftyInsta.Users] crashes

esabunor opened this issue · comments

hi I've been trying to save the array of users returned by this call:

handler.users.followed(byUser: .me, usersMatchinQuery: nil, with: .init(maxPagesToLoad: .max), updateHandler: { (response, users, pag, otherUsers) in
            
        }) { (result, pag) in
            do {
                try self.followedUsers = result.get()
                let encodedData: Data =  NSKeyedArchiver.archivedData(withRootObject:self.followedUsers.map{$0.rawResponse})
                UserDefaults.standard.set(encodedData, forKey: "\(self.account.username)-followedUsers")
                UserDefaults.standard.synchronize()
            } catch {
                print(error)
            }
        }

but it crashes with this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance

It's failing to encode the enum cases' associated values.
Unfortunately the "best" fix, making DynamicResponse Codable, is not that immediate. Not for DynamicResponse per se, but in order to make it work with the rest of the library.

A "temporary" solution (meaning I would still suggest building yourself a Codable struct to persist), if you really wanna use DynamicResponse directly, is to rely on JSONSerialization:

  • store followedUsers.map { $0.beautifiedDescription }.
  • when you retrieve it do
let object = JSONSerialization.jsonObject(with: theRetrievedString.data(using: .utf8)!, options: [])
let response = DynamicResponse(object)

I would not recommend this over persisting a custom User struct like this.

struct User: Codable {
   var primaryKey: Int
   var username: String
  var name: String?
  var thumbnail: URL?
}