Apple platforms quickstart (SwiftUI)
A SwiftUI app for iPhone, iPad and Mac that shows CMS Orbit pages by their address, draws components with your own views and refreshes when content changes.
Tutorial19 min read
This guide builds a SwiftUI app for Northwilds that shows the pages editors publish in CMS Orbit. Each page opens by its address, from the CMS menu or from a link on another page. Components are drawn by your own SwiftUI views, picked from a component map. Drafts can be shown through your own server, and pages refresh when people pull down, when the app returns to the foreground and, if you want, when your server is told that editors published.
The same code builds for iOS, iPadOS and macOS.
Tested with: Xcode 27.0, Swift 6.4 in Swift 6 language mode, the iOS 26.3 Simulator and a macOS 27 build, and the Swift SDK CMSOrbit 0.2.0.
Prefer to start from a working project? Use the starter: bifrost-orbit/cms-starter-apple, the finished code of this guide.
Before you start
You need:
- Xcode 16 or later. The app targets iOS 17 and macOS 14, so it can use
NavigationStackandContentUnavailableView. The SDK itself runs from iOS 15 and macOS 12. - A CMS Orbit space with at least one published page, such as the home page at
/. - A public key, starting with
cms_pk_, from Configuration › API keys. It reads published content only, so it may ship inside the app. Step 4 of Connect a website shows how to create it. - The API address and the region key. The address is
https://api.bifrostorbit.com/cms. The region key is under Configuration › Environments, such asglobalorgermany.
You do not need the secret cms_sk_ key in the app, and it must never be put there. Step 7 explains why and what to do instead.
1Create the project
In Xcode, choose File › New › Project…, then Multiplatform › App. Name it Northwilds, choose SwiftUI for the interface and save it.
Select the Northwilds target, open General and set Minimum Deployments to iOS 17.0 and macOS 14.0.
For the Mac, open Signing & Capabilities, find App Sandbox and tick Outgoing Connections (Client). Without it, the Mac app cannot reach the CMS. iOS needs nothing extra, because the API is served over https.
2Install the SDK
Choose File › Add Package Dependencies…, enter https://github.com/bifrost-orbit/cms-sdk-swift, keep Up to Next Major Version from 0.2.0, and add the CMSOrbit library to the Northwilds target.
In a Package.swift, the same dependency is:
dependencies: [ .package(url: "https://github.com/bifrost-orbit/cms-sdk-swift", from: "0.2.0"),],targets: [ .target(name: "Northwilds", dependencies: [.product(name: "CMSOrbit", package: "cms-sdk-swift")]),]3Add the settings
Add a new Swift file with the app's settings:
// Northwilds/CMSSettings.swiftimport Foundationenum CMSSettings { static let apiURL = URL(string: "https://api.bifrostorbit.com/cms")! static let publicKey = "cms_pk_…" static let region = "global" static let locale: String? = nil static let websiteHost = "northwilds.com"}regionis your region key.localecan staynil, so the region's default language answers, or name one, such asde-DE.websiteHostis your website's domain. Links to it open inside the app instead of in the browser.
The public key is safe in the app: anyone who unpacks the app can read it, and all it can do is read what is already published. A key belongs to one environment. To build a test version against Staging, use the Staging address, https://api-stage.bifrostorbit.com/cms, and a public key from Staging, for example inside #if DEBUG.
4Create the client
Create one client for the whole app:
// Northwilds/CMS.swiftimport CMSOrbitimport Foundationlet cms: CMSOrbitClient = { let configuration = URLSessionConfiguration.default configuration.requestCachePolicy = .reloadIgnoringLocalCacheData configuration.urlCache = nil do { return try CMSOrbitClient( apiKey: CMSSettings.publicKey, baseURL: CMSSettings.apiURL, region: CMSSettings.region, locale: CMSSettings.locale, session: URLSession(configuration: configuration) ) } catch { fatalError("Check CMSSettings.swift: \(error.localizedDescription)") }}()The client is Sendable, so a single shared instance is safe under Swift 6 strict concurrency. It refuses a cms_sk_ key, and stops the app at launch if the settings are wrong, so a mistake shows up straight away.
The session has no URLSession cache. The CMS's cache headers are written for shared caches such as a CDN, so the app keeps its own copy of each page instead, with a lifetime you choose (step 8).
5Show a page by its address
Every CMS page has an address, such as / or /trips/lofoten-ridge-walk. The app opens pages by address, the way a website does, so the CMS menu and links inside pages work without extra code.
First the screen that shows one address:
// Northwilds/PageScreen.swiftimport CMSOrbitimport SwiftUIstruct PageScreen: View { let path: String @State private var state = LoadState.loading @Environment(\.openURL) private var openURL enum LoadState { case loading case page(CMSPage) case notFound case failed(String) } var body: some View { Group { switch state { case .loading: ProgressView() case .page(let page): PageView(page: page) case .notFound: ContentUnavailableView("Page not found", systemImage: "map", description: Text("Nothing is published at \(path).")) case .failed(let message): ContentUnavailableView("The page could not be loaded", systemImage: "wifi.exclamationmark", description: Text(message)) } } .task(id: path) { await load(path) } } private func load(_ path: String) async { do { switch try await cms.resolve(path) { case .page(let page): state = .page(page) case .redirect(let redirect): if redirect.to.hasPrefix("/") { await load(redirect.to) } else if let url = URL(string: redirect.to) { openURL(url) } case .gone, .notFound: state = .notFound } } catch is CancellationError { } catch { state = .failed(error.localizedDescription) } }}struct PageView: View { let page: CMSPage var body: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 40) { ForEach(page.components) { BlockView(block: $0) } } .padding() } .navigationTitle(page.name) .toolbar { if let seo = page.seo, let url = URL(string: seo.canonical) { ToolbarItem { ShareLink(item: url, subject: Text(seo.title), message: Text(seo.description)) } } } }}resolvesays what an address is. A page is shown. A redirect, such as one made when an editor moved the page, is followed: inside the app for an address on your website, in the browser for one elsewhere. A removed or unknown address shows "Page not found".- The page's name is the screen title. The page's SEO title, description and public address go into the share sheet, so a shared Northwilds trip arrives as a proper link to the website.
BlockViewdraws each component. You write it in step 6.
Then the root view, with a navigation stack, the CMS menu and one place that decides where links go:
// Northwilds/ContentView.swiftimport CMSOrbitimport SwiftUIstruct CMSAddress: Hashable { let path: String}struct ContentView: View { @State private var stack: [CMSAddress] = [] @State private var menu: [CMSNavItem] = [] @Environment(\.openURL) private var openOutside var body: some View { NavigationStack(path: $stack) { PageScreen(path: "/") .navigationDestination(for: CMSAddress.self) { PageScreen(path: $0.path) } .toolbar { ToolbarItem { Menu { ForEach(menu, id: \.self) { item in if item.children.isEmpty { Button(item.label) { open(item.href) } } else { Menu(item.label) { ForEach(item.children, id: \.self) { child in Button(child.label) { open(child.href) } } } } } } label: { Label("Menu", systemImage: "line.3.horizontal") } } } } .environment(\.openURL, OpenURLAction { url in guard let path = Self.appPath(url) else { return .systemAction } stack.append(CMSAddress(path: path)) return .handled }) .task { menu = (try? await cms.navigation("header").items) ?? [] } } private func open(_ href: String?) { guard let href, let url = URL(string: href) else { return } if let path = Self.appPath(url) { stack.append(CMSAddress(path: path)) } else { openOutside(url) } } static func appPath(_ url: URL) -> String? { guard url.host == nil || url.host == CMSSettings.websiteHost else { return nil } return url.path.isEmpty ? "/" : url.path }}- The menu comes from Menus in the CMS, read by its key, here
header. Use the key of your own menu. - The
openURLaction catches everyLinkinside the stack, including links in rich text. Addresses on your website, such as/tripsorhttps://northwilds.com/trips, open as a new screen. Anything else opens in the browser.
The app file stays as Xcode made it:
// Northwilds/NorthwildsApp.swiftimport SwiftUI@mainstruct NorthwildsApp: App { var body: some Scene { WindowGroup { ContentView() } }}The app does not build yet: BlockView comes next.
6Write components as SwiftUI views
Editors build pages from components, such as a hero or a feature spotlight. Each block on a page has an id, a type (the component's key), fields, and children, the blocks in each slot. The app draws each type with a SwiftUI view, chosen from a component map.
This guide uses three components: hero, featureSpotlight and action, a button placed in the others' slots. Use the keys and fields of your own space's components, which you can see in Components in the CMS, or let the type generator write the structs, as described in The Swift SDK.
Describe the fields of each component with a struct:
// Northwilds/Components/Blocks.swiftimport CMSOrbitstruct HeroBlock: CMSBlockFields { static let blockType = "hero" var eyebrow: String? var heading: String var headingAccent: String? var description: CMSRichText?}struct FeatureSpotlightBlock: CMSBlockFields { static let blockType = "featureSpotlight" var eyebrow: String? var heading: String var body: CMSRichText? var image: CMSImage?}struct ActionBlock: CMSBlockFields { static let blockType = "action" var label: String var link: CMSLink? var style: String?}Make optional every field an editor may leave empty. A field the struct does not list is ignored, so the CMS can gain fields without breaking the app.
Then the component map, the view that draws any block, and a fallback for types the app does not know yet:
// Northwilds/Components/ComponentMap.swiftimport CMSOrbitimport SwiftUI@MainActorenum ComponentMap { static let views: [String: (CMSComponent) -> AnyView] = [ HeroBlock.blockType: view(HeroBlock.self) { HeroView(hero: $0, block: $1) }, FeatureSpotlightBlock.blockType: view(FeatureSpotlightBlock.self) { FeatureSpotlightView(spotlight: $0, block: $1) }, ActionBlock.blockType: view(ActionBlock.self) { action, _ in ActionView(action: action) }, ] private static func view<Fields: CMSBlockFields, Content: View>( _ type: Fields.Type, _ make: @escaping (Fields, CMSComponent) -> Content ) -> (CMSComponent) -> AnyView { { block in guard let fields = try? block.decode(Fields.self) else { return AnyView(UnknownBlockView(block: block)) } return AnyView(make(fields, block)) } }}struct BlockView: View { let block: CMSComponent var body: some View { if let make = ComponentMap.views[block.type] { make(block) } else { UnknownBlockView(block: block) } }}struct SlotView: View { let block: CMSComponent let slot: String var body: some View { ForEach(block.children[slot] ?? []) { BlockView(block: $0) } }}struct UnknownBlockView: View { let block: CMSComponent var body: some View { #if DEBUG Text("No view for \(block.type)") .font(.caption.monospaced()) .foregroundStyle(.secondary) #endif }}- To add a component, write its struct and view, and add one line to
views. - Debug builds name each component the app cannot draw yet. Release builds draw nothing for it, so a new component in the CMS never breaks an app already in the App Store.
SlotViewdraws nested blocks. Since it usesBlockView, slots can hold any component, at any depth.
The views:
// Northwilds/Components/HeroView.swiftimport CMSOrbitimport SwiftUIstruct HeroView: View { let hero: HeroBlock let block: CMSComponent var body: some View { VStack(alignment: .leading, spacing: 12) { if let eyebrow = hero.eyebrow { Text(eyebrow.uppercased()) .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) } Text(hero.heading) .font(.largeTitle.bold()) if let accent = hero.headingAccent { Text(accent) .font(.title2) .foregroundStyle(.secondary) } if let description = hero.description { RichText(html: description) } HStack { SlotView(block: block, slot: "primaryAction") SlotView(block: block, slot: "secondaryAction") } } }}// Northwilds/Components/FeatureSpotlightView.swiftimport CMSOrbitimport SwiftUIstruct FeatureSpotlightView: View { let spotlight: FeatureSpotlightBlock let block: CMSComponent var body: some View { VStack(alignment: .leading, spacing: 12) { if let url = spotlight.image?.url(width: 1200) { AsyncImage(url: url) { image in image.resizable().scaledToFit() } placeholder: { Color.secondary.opacity(0.1).frame(height: 200) } .clipShape(RoundedRectangle(cornerRadius: 12)) .accessibilityLabel(spotlight.image?.alt ?? "") } if let eyebrow = spotlight.eyebrow { Text(eyebrow.uppercased()) .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) } Text(spotlight.heading) .font(.title.bold()) if let body = spotlight.body { RichText(html: body) } SlotView(block: block, slot: "action") } }}// Northwilds/Components/ActionView.swiftimport SwiftUIstruct ActionView: View { let action: ActionBlock var body: some View { if let href = action.link?.href, let url = URL(string: href) { if action.style == "primary" { Link(action.label, destination: url).buttonStyle(.borderedProminent) } else { Link(action.label, destination: url).buttonStyle(.bordered) } } }}image.url(width: 1200)asks the CMS for a resized copy, so the app never downloads the original upload. The image's alt text becomes its accessibility label.- A link's
hrefalready holds the target page's current address, soLinkopens it, and theopenURLaction from step 5 decides whether it stays in the app.
Rich text arrives as HTML. This small view turns it into an AttributedString with the system font, bold text and working links:
// Northwilds/Components/RichText.swiftimport SwiftUIstruct RichText: View { let html: String var body: some View { Text(Self.attributed(html)) } static func attributed(_ html: String) -> AttributedString { let styled = "<style>body { font-family: -apple-system; font-size: 17px; }</style>" + html guard let string = try? NSMutableAttributedString( data: Data(styled.utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil ) else { return AttributedString(html) } string.removeAttribute(.foregroundColor, range: NSRange(location: 0, length: string.length)) while string.string.hasSuffix("\n") { string.deleteCharacters(in: NSRange(location: string.length - 1, length: 1)) } return AttributedString(string) }}It removes the HTML's text colour so dark mode works, and keeps a fixed text size. It does not draw list bullets. For long articles, tables or embedded media, show the HTML in a WKWebView or use a Markdown or HTML library you already trust.
Run the app on an iPhone simulator. The home page shows its components, the menu opens other pages, and an address with nothing published shows "Page not found".
7Show drafts (through your own server, or not at all)
Be clear about what the app can and cannot do here.
- The editor's live preview shows your website, not your app. The CMS opens the space's Preview URL in a frame beside the editor. There is no bridge script,
data-cms-idor click-to-select for a native app. - Drafts are read with the secret
cms_sk_key, and it must never ship in an app. Anything inside an app can be read by whoever installs it. The SDK refuses apreviewKeyon iOS, iPadOS, tvOS, watchOS and visionOS for that reason.
That leaves two honest options.
Skip drafts in the app. Editors check their pages in the website's live preview, and the team tests the app with a build that reads Staging (step 3). Published Staging content is then the app's preview. This is what most apps need.
Show drafts through your own server. Your server holds the secret key, checks the editor's preview token and sends back the draft. The app never sees the key. It works like this:
- A preview link, such as
https://northwilds.com/trips/lofoten-ridge-walk?preview=eyJ…, opens the app. For that, the app needs an associated domain (a universal link) for your website. The editor's live preview does not open the app by itself: someone opens the link on the device. - The app reads the token and asks your server for the draft.
- Your server checks the token with CMS Orbit, reads the draft with the secret key and answers with the page.
Add your server's address to the settings:
// Northwilds/CMSSettings.swift, inside CMSSettings static let draftServerURL = URL(string: "https://northwilds.com/api/app-preview")!Add a screen that shows a draft:
// Northwilds/DraftScreen.swiftimport CMSOrbitimport SwiftUIstruct PreviewLink: Identifiable { let token: String var id: String { token }}struct DraftScreen: View { let link: PreviewLink @State private var page: CMSPage? @State private var message: String? var body: some View { NavigationStack { if let page { PageView(page: page) } else if let message { ContentUnavailableView("No preview", systemImage: "eye.slash", description: Text(message)) } else { ProgressView() } } .task { do { page = try await Self.draft(token: link.token) } catch { message = "The preview link has expired. Open it again from the editor." } } } static func draft(token: String) async throws -> CMSPage { var address = URLComponents(url: CMSSettings.draftServerURL, resolvingAgainstBaseURL: false)! address.queryItems = [URLQueryItem(name: "token", value: token)] let (data, response) = try await URLSession.shared.data(from: address.url!) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.userAuthenticationRequired) } return try JSONDecoder().decode(CMSPage.self, from: data) }}In ContentView, add the preview link to the state and open the sheet when a link with a token arrives:
// Northwilds/ContentView.swift, next to the other @State properties @State private var preview: PreviewLink?// Northwilds/ContentView.swift, before .task on the NavigationStack .onOpenURL { url in if let token = CMSOrbitClient.previewToken(from: url) { preview = PreviewLink(token: token) } else if let path = Self.appPath(url) { stack = [CMSAddress(path: path)] } } .sheet(item: $preview) { DraftScreen(link: $0) }A universal link without a token opens that page, so links to northwilds.com shared in messages also land in the app.
On your server, the endpoint does three things. In server-side Swift, on macOS or Linux, the SDK accepts the secret key:
// Server: DraftPage.swiftimport CMSOrbitimport Foundationlet env = ProcessInfo.processInfo.environmentlet cms = try CMSOrbitClient( apiKey: env["CMS_PUBLIC_KEY"]!, baseURL: URL(string: env["CMS_API_URL"]!)!, region: env["CMS_DEFAULT_REGION"], previewKey: env["CMS_PREVIEW_KEY"])func draftPage(token: String) async throws -> Data { let session = try await cms.verifyPreview(token: token) guard let url = session.url else { throw CMSOrbitError.notFound(message: "This entry has no page") } let page = try await cms.page(url, options: CMSRequestOptions(preview: true)) return try JSONEncoder().encode(page)}Answer 200 with that JSON, or 401 when draftPage throws .unauthorized, which means the token is invalid or has expired (tokens last an hour). In any other language, the same steps are described in Preview without Next.js in Connect a website without Next.js: check the token at /preview?token=…, then read the page with the secret key and draft=true.
Secret keys exist for Staging only, so the server uses Staging's public and secret keys. Keep the endpoint to preview tokens: it must not read any draft for anyone who asks.
8Refresh when editors publish
An app has no CDN cache to purge. What it has is its own copy of each page, and the question is when to read it again. A good default:
- keep each page in memory for a few minutes, so moving back and forth does not read it again;
- read it again when someone pulls down on the page;
- read it again when the app returns to the foreground, if the copy is older than its lifetime;
- keep showing the last copy when the network is gone.
Add a small cache:
// Northwilds/PageCache.swiftimport CMSOrbitimport Foundationactor PageCache { static let shared = PageCache() private let lifetime: TimeInterval = 5 * 60 private var entries: [String: (resolution: CMSResolution, loadedAt: Date)] = [:] func resolve(_ path: String, fresh: Bool = false) async throws -> CMSResolution { if !fresh, let entry = entries[path], Date.now.timeIntervalSince(entry.loadedAt) < lifetime { return entry.resolution } do { let resolution = try await cms.resolve(path) entries[path] = (resolution, .now) return resolution } catch { if let entry = entries[path] { return entry.resolution } throw error } } func clear() { entries.removeAll() }}Then let PageScreen read through it, with pull to refresh and a check when the app comes back:
// Northwilds/PageScreen.swiftimport CMSOrbitimport SwiftUIstruct PageScreen: View { let path: String @State private var state = LoadState.loading @Environment(\.openURL) private var openURL @Environment(\.scenePhase) private var scenePhase enum LoadState { case loading case page(CMSPage) case notFound case failed(String) } var body: some View { Group { switch state { case .loading: ProgressView() case .page(let page): PageView(page: page) .refreshable { await load(path, fresh: true) } case .notFound: ContentUnavailableView("Page not found", systemImage: "map", description: Text("Nothing is published at \(path).")) case .failed(let message): ContentUnavailableView("The page could not be loaded", systemImage: "wifi.exclamationmark", description: Text(message)) } } .task(id: path) { await load(path) } .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await load(path) } } } } private func load(_ path: String, fresh: Bool = false) async { do { switch try await PageCache.shared.resolve(path, fresh: fresh) { case .page(let page): state = .page(page) case .redirect(let redirect): if redirect.to.hasPrefix("/") { await load(redirect.to, fresh: fresh) } else if let url = URL(string: redirect.to) { openURL(url) } case .gone, .notFound: state = .notFound } } catch is CancellationError { } catch { state = .failed(error.localizedDescription) } }}PageView stays at the bottom of the file, as in step 5.
The cache lives in memory, so a new launch reads everything again. To open instantly and offline after a restart, also write each page to the app's caches folder: CMSPage is Codable.
The delivery API lets its own cache keep published answers briefly, so a page an editor has just published can take a minute or so to appear, even after pulling down.
Refresh from your server (optional). To update the app within seconds of publishing, let your server receive CMS Orbit's webhook and pass it on as a silent push notification:
- Add a webhook in Configuration › Webhooks that points at your server.
- On your server, check the signature before trusting the message.
- Send a background push with
content-available: 1through Apple Push Notification service to the app. - In the app, call
await PageCache.shared.clear()when the push arrives, so every page is read again the next time it is shown.
On a Swift server, CMSWebhook.parse from the SDK checks the signature and the timestamp. With Vapor:
// Server: routes.swiftimport CMSOrbitimport Vaporapp.post("api", "cms-webhook") { req async -> HTTPStatus in guard let message = CMSWebhook.parse( secret: Environment.get("CMS_WEBHOOK_SECRET")!, timestamp: req.headers.first(name: CMSWebhook.timestampHeader) ?? "", signature: req.headers.first(name: CMSWebhook.signatureHeader) ?? "", body: req.body.string ?? "" ) else { return .unauthorized } if message.event != "webhook.test" { Task { await sendRefreshPush() } } return .noContent}It takes the raw request body, the x-orbit-timestamp and x-orbit-signature headers, and the webhook secret, including whsec_, and answers nil when the message is not genuine or is more than five minutes old. Answer 401 then, and 2xx quickly otherwise, then send the push. CMSWebhook uses CryptoKit, so it is there when the server runs on macOS; on Linux, check the signature with swift-crypto as Webhooks describes. Background pushes are a hint to the system, not a promise: iOS may delay or drop them, so keep the cache lifetime and pull to refresh as well.
Next steps
- The Swift SDK: every method, your own types, generated types and errors.
- Render components: how pages are built from components and slots.
- Set up the live preview: how the editor's preview works for websites.
- Webhooks: every event, retries and the delivery log.
- Caching and refreshing pages: what each change refreshes.
- Regions and languages: reading other regions and showing fallbacks.
- SEO with the SDK: the metadata each page carries.
- Keys, permissions and sign-in: which key goes where.
- Troubleshooting: when a page does not appear.
Was this page helpful?