3

I have a custom struct that has properties of types that are other structs with non codable types. It is a complex tree of structs within structs, and I need to convert it to Data so I can save it.

I need to save this struct (chat)

struct Chat{
    var dictOfRecentMessages:[String:Message] = [:]
    var matchPicture:UIImage? 
    var metadata:JSON?
}

    struct Message{
        let messageID:String
        var chatID:String
        let whoSent:String
        let timeTriedToSend:Int


        var messageString:String?
        var image:ImageMessage?
        var video:VideoMessage?
        var location:LocationMessage?
        let status:String 

    }

struct ImageMessage{
    var uiImage:UIImage?
    var imageURL:String?
    var imageSize:CGSize?
}
struct VideoMessage{
    var video:NSURL?
    var videoURL:String?
}
struct LocationMessage{
    var clLocation:CLLocation?
    var mapCamera:MKMapCamera?
    var mapSnapshot:MKMapSnapshot?
}

Is serialization the best way to go, like in this post? Swift structs to NSData and back

I have tried conforming to Codable but it gives an error saying it does not conform, which is expected due to the types.

Meme Stream
  • 171
  • 2
  • 11
  • 1
    Please post object's code and what you've tried – Leo Jul 06 '18 at 13:18
  • the inner structs should also conform to **Codable** – Shehata Gamal Jul 06 '18 at 13:27
  • I just updated it so you can see the inner structs - they contain non simple types that mean the struct cannot conform to codable, for example MKMapSnapshot – Meme Stream Jul 06 '18 at 13:28
  • For `MKMapSnapshot`: https://stackoverflow.com/questions/25471657/keep-mkmapsnapshotter-as-nsdata-in-memory-swift You need a way for each part to save/retrieve/init them from/to `(NS)Data`. Work on each difficult object first, then you'll work on the whole one. – Larme Jul 06 '18 at 13:42
  • ok, that was just an example, I do not want to have to manually go into every type used throughout the struct and convert to NSData. Is there no way of coverting the whole thing straight up into Data through serialization, or should I just create a new struct that has only codable types and just save that. – Meme Stream Jul 06 '18 at 13:59
  • You have to. At some point it will have to transform one (sub)property into NSData. – Larme Jul 06 '18 at 14:33
  • In you structure some of the type does not conform to Codable, So you are getting same error: Please see this: https://stackoverflow.com/questions/46197785/how-to-conform-uiimage-to-codable – Sagar Chauhan Jul 06 '18 at 17:29

0 Answers0