Sunday, 1 September 2019

Switching contentTypeId while fetching data from Contentful

I'm trying to display some FAQs content in my app using contentful, below is my UserFAQs.swift class which I'm using to fetch the data and this works fine. Now I have a new requirement for adding FAQs for guest user. Only the data is different per user all other things are the same. So, I created a duplicate content model of my existing userFAQs called guestFAQs and added the content for it. In my below class here they both work individually for eg: if I set contentTypeId = “guestFAQs” or contentTypeId = "userFAQs" in my below class it works fine. But I need to fetch based on the user type and when I set the contentTypeId based on the condition below it always gives me the result as "userFAQs" even when the userType is guest. Am I missing something here? Any help is appreciated. This is the library that I'm using.

import UIKit
import Contentful

final class UserFAQs: EntryDecodable, FieldKeysQueryable, Resource {

    static var contentTypeId = (Utilities.userType == .normalUser) ? "userFAQs" : "guestFAQs"

    let sys: Sys
    var sectionIndex: Int?
    var sectionName: String?
    var questionName: String?
    var answer: String?

    // MARK: Initialization
    public required init(from decoder: Decoder) throws {
        print("APIName = \(UserFAQs.contentTypeId)")
        sys         = try decoder.sys()
        let fields      = try decoder.contentfulFieldsContainer(keyedBy: UserFAQs.FieldKeys.self)

        sectionIndex       = try fields.decodeIfPresent(Int.self, forKey: .sectionIndex)
        sectionName      = try fields.decodeIfPresent(String.self, forKey: .sectionTitle)
        questionName       = try fields.decodeIfPresent(String.self, forKey: .questionName)
        answer    = try fields.decodeIfPresent(String.self, forKey: .sectionText)
    }

    enum FieldKeys: String, CodingKey {
        case sectionIndex, sectionTitle, questionName, sectionText
    }
}



from Switching contentTypeId while fetching data from Contentful

No comments:

Post a Comment