Contentful logo

Contentful Community

Casting troubles using Contentful with SwiftUI

Hello Contentful community!

I’m a (very) new developer trying to use Contentful in a SwiftUI project, and I’m running into some casting errors. I’m trying to access two strings stored in Contentful and append them to an array. I’m getting this error message when I try to print the results:

Could not cast value of type ‘Contentful.Link’ (0x10c3faa88) to ‘Swift.String’ (0x7fff87a77fc0).

2020-03-16 20:12:04.985833+0000 Layered City[20556:2903713] Could not cast value of type ‘Contentful.Link’ (0x10c3faa88) to ‘Swift.String’ (0x7fff87a77fc0).

Here’s the rest of my code. Ultimately, I’m trying to get the “channel” data from my content model on Contentful so that it is accessible within my SwiftUI views. Forgive me being a total newbie at this — I’m using this Coronavirus situation to try to learn some basic iOS development skills. Here’s the rest of my code:

import SwiftUI
import Contentful
import Combine

// I'm trying to make a structure that I can fill with Contentful data
// Maybe I don't need to do this or there's a better way?

struct Channel: Identifiable {
    let id = UUID()
    var channelName: String
    var publisher: String
}

// This is an array of fake data that simulates content from Contentful
// Again, maybe I don't need to do this or there's a better way?

var channelData = [
    Channel(
        channelName: "Planet Money",
        publisher: "NPR"),
    Channel(
        channelName: "The Indicator",
        publisher: "NPR"),
]

// I changed the spaceid and accessToken below for this public forum example
let client = Client(spaceId: "bl6xhrcd316q", accessToken: "btCMYzILHdhtZGIE-BjXN2vksuSjR2LeDonHQo51xS0")

func getArray(id: String, completion: @escaping([Entry]) -> ()) {
    let query = Query.where(contentTypeId: id)
    client.fetchArray(of: Entry.self, matching: query) { result in
        switch result {
            case .success(let array):
            DispatchQueue.main.async {
                completion(array.items)
                }
            case .error(let error):
            print(error)
        }
    }
}

class ChannelStore: ObservableObject {

  @Published var channels: [Channel] = channelData

    init() {
        getArray(id: "channel") { (items) in
            items.forEach { (item) in
                self.channels.append(Channel(
                    channelName: item.fields["channelName"] as! String,
                    publisher: item.fields["publisher"] as! String))
                }
            }
    }
}