Giter VIP home page Giter VIP logo

Comments (12)

gKamelo avatar gKamelo commented on August 11, 2024 3

Hey Tomek xD

+1 for Link support in RichTextDocument as that's the only puzzle that we need to have to fully support persistence;)

from contentful-persistence.swift.

robatum avatar robatum commented on August 11, 2024 2

Hey Tomasz,

thanks for your fast reply and taking the time to look into the issue!

I noticed there is a typo in my example Core Data model. There should be fileType for Asset Model but is filetype instead.

No worries that was a quick fix :-)

Anyway, I think you're right that it seems impossible to persist more complex RichTextDocument at the moment. Link class seems to be the main limitation as I am check in the code. I'll open the issue on our internal tracker. Thanks!

+1 Would be great to have this feature included as the persistence/syncing works flawless otherwise and we would prefer to use it over a custom implementation.

Have a great weekend!

Best Andreas

from contentful-persistence.swift.

pknuth avatar pknuth commented on August 11, 2024 2

+1, can we make it happen like today? XD

from contentful-persistence.swift.

tomkowz avatar tomkowz commented on August 11, 2024

@robatum Hey, sorry for late response!

The RichTextDocument is designed to be stored in the Core Data using Transformable type.

In order to do store RichTextDocument in Core Data you need to follow these steps:

  1. Create a type for your Core Data entity and make sure the fieldMapping is set for the RichTextDocument field (content in my case).
import Contentful
import ContentfulPersistence
import CoreData

final class Article: NSManagedObject, EntryPersistable {
    static var contentTypeId: ContentTypeId = "article"

    @NSManaged var id: String
    @NSManaged var localeCode: String?
    @NSManaged var createdAt: Date?
    @NSManaged var updatedAt: Date?

    @NSManaged var title: String
    @NSManaged var content: RichTextDocument

    static func fieldMapping() -> [FieldName : String] {
        return [
            "title": "title",
            "content": "content"
        ]
    }
}
  1. Create value transformer:
import Contentful
import Foundation

final class RichTextDocumentTransformer: ValueTransformer {
    override class func transformedValueClass() -> AnyClass {
        NSData.self
    }

    override func transformedValue(_ value: Any?) -> Any? {
        guard let text = value as? RichTextDocument else { return nil }

        return try! NSKeyedArchiver.archivedData(withRootObject: text, requiringSecureCoding: false)
    }

    override class func allowsReverseTransformation() -> Bool {
        true
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? {
        guard let data = value as? Data else { return nil }
        return try! NSKeyedUnarchiver.unarchivedObject(ofClass: RichTextDocument.self, from: data)
    }
}
  1. Add attribute with a type Transformable to Core Data entity and set:
  • Transformer: RichTextDocumentTransformer
  • Custom Class: RichTextDocument
  • Module: Current Product Module - make sure this is set.

Let me know if that works for you.

Example Project

from contentful-persistence.swift.

tomkowz avatar tomkowz commented on August 11, 2024

No update in this thread. I am closing this for now.

from contentful-persistence.swift.

robatum avatar robatum commented on August 11, 2024

Hey Tomasz,

thank you very much for your reply and your excellent example!! I tried a similar approach based on NSSecureUnarchiveFromDataTransformer but couldn't make RichTextDocument conform to NSSecureCoding ;-) .

Your approach is working for me but with one (important) limitation: As long as my RichTextDocument only consists of Text Blocks and Paragraphs all is fine but as soon as I'm embedding an Asset (Picture) or Embed to the Document the decoding fails for me.

This is my DocumentTransformer right now (Sry for the poor formatting, for some reason the highlighting feature doesn't take the whole code sample):

`
import Contentful
import Foundation

@objc(RichTextDocumentTransformer)
final class RichTextDocumentTransformer: ValueTransformer {

override class func transformedValueClass() -> AnyClass {
NSData.self
}

override func transformedValue(_ value: Any?) -> Any? {
guard let text = value as? RichTextDocument else { return nil }

    do {
        let result = try NSKeyedArchiver.archivedData(withRootObject: text, requiringSecureCoding: false)
        return result
    } catch {
        Logger.error("Couldn't archive contentful data: \(error)")
        return nil
    }
}

override class func allowsReverseTransformation() -> Bool {
    true
}

override func reverseTransformedValue(_ value: Any?) -> Any? {
    guard let data = value as? Data else { return nil }
    do {
        guard let result = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? RichTextDocument else {                    
                                         //NSKeyedUnarchiver.unarchivedObject(ofClass: RichTextDocument.self, from: data) else {
            Logger.error("Couldn't cast to RichTextDocument.")
            return nil
        }
        return result
    } catch {
        Logger.error("Couldn't unarchive contentful data: \(error)")
        return nil
    }   
}

}

extension Contentful.RichTextDocument: NSSecureCoding {

public static var supportsSecureCoding = false

} `

The error which I receive is:

🚨 Error ⏱ 06/25/2020 05:26:28:239 📂 RichTextDocumentTransformer.swift:41 : Couldn't cast to RichTextDocument.
valueNotFound(Swift.KeyedDecodingContainer<Contentful.Link.Sys.(unknown context at $104be348c).CodingKeys>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 2", intValue: 2), NodeContentCodingKeys(stringValue: "data", intValue: nil), JSONCodingKeys(stringValue: "target", intValue: nil), CodingKeys(stringValue: "sys", intValue: nil)], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil))

I also tried to run the demo project you've provided which gave me a different but related error, but this time already while encoding the document:

Screenshot 2020-06-25 at 05 38 37

I'm currently working with Xcode 11.5 on MacOS 10.15.4, I'm using these pods:
pod 'Contentful' , '5.0.11' pod 'ContentfulPersistenceSwift' , '0.15.0'

Also tried the most recent version but without any differences. In case you have another idea, I'm open for recommandations :-).

Thx in advance!

Best Andreas

from contentful-persistence.swift.

tomkowz avatar tomkowz commented on August 11, 2024

Hey Andreas!

I noticed there is a typo in my example Core Data model. There should be fileType for Asset Model but is filetype instead.

Also sorry for the example not running as expected. I forgot that the space and the specific article are used as a base for another thing I am working right now so, indeed the project could crash.

Anyway, I think you're right that it seems impossible to persist more complex RichTextDocument at the moment. Link class seems to be the main limitation as I am check in the code. I'll open the issue on our internal tracker. Thanks!

Best,
Tomasz

from contentful-persistence.swift.

SDC-KurtTreangen avatar SDC-KurtTreangen commented on August 11, 2024

Hello @tomkowz, apologies if this is the wrong thread but just wanted to check if there are any updates regarding...

Anyway, I think you're right that it seems impossible to persist more complex RichTextDocument at the moment. Link class seems to be the main limitation as I am check in the code. I'll open the issue on our internal tracker. Thanks!

Our content team is currently trying to leverage Links within within rich text so this would be greatly appreciated.

from contentful-persistence.swift.

mariuskatcontentful avatar mariuskatcontentful commented on August 11, 2024

@SDC-KurtTreangen this should now be fixed if you could check and verify.

from contentful-persistence.swift.

SDC-KurtTreangen avatar SDC-KurtTreangen commented on August 11, 2024

Hello @mariuskatcontentful ,

When attempting to test the fix that was included with https://github.com/contentful/contentful.swift/tree/5.5.1 I receive the following error when using CocoaPods.

[!] CocoaPods could not find compatible versions for pod "Contentful":
  In Podfile:
    Contentful (~> 5.5.1)

    ContentfulPersistenceSwift was resolved to 0.17.4, which depends on
      Contentful (~> 5.4.1)

from contentful-persistence.swift.

mariuskatcontentful avatar mariuskatcontentful commented on August 11, 2024

@SDC-KurtTreangen Thanks for catching that. I sorted it if you want to check again.

from contentful-persistence.swift.

SDC-KurtTreangen avatar SDC-KurtTreangen commented on August 11, 2024

Sorry for the late response @mariuskatcontentful . Everything is working as expected with the latest version. Thanks!

The solution on our end was to switch on the Link. If entryDecodable, cast it to our custom protocol for representing in line links, if entry or unresolved fetch the link from our local CoreDataStore by its id. This allows us to load rich text with in line links from CoreData and from the Client API.

from contentful-persistence.swift.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.