### Pages API Usage Example with Search Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Practical example demonstrating searchPages method usage with ButterCMS. Shows how to configure search parameters including query, page type, locale, pagination settings, and handle the async Result response for success/failure cases. ```swift butter.searchPages(parameters: [ .query(value: "Automotive"), .pageType(value: "case_studies"), .locale(value: "en"), .page(value: 1), .pageSize(value: 10) ], type: CaseStudyPageFields.self) { result in switch result { case .success(let pages): ..... case .failure(let error): ..... } } ``` -------------------------------- ### Install CocoaPods Dependency Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Instructions for installing the ButterCMS SDK using CocoaPods. This involves initializing a Podfile, updating it with the SDK dependency, and then running the install command. ```bash $ brew install cocoapods $ pod init open -a Xcode Podfile target 'YourAppName' do use_frameworks! pod 'ButterCMSSDK', '1.0.7' end $ pod install ``` -------------------------------- ### Collection API Usage Example Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Example showing how to use getCollection method to fetch collection items. Demonstrates passing a collection slug and the FaqItem type that implements CollectionItem protocol, with completion handler for handling the async result. ```swift butter.getCollection(slug: "faq", type: FaqItem.self) { result in // do something with the result } ``` -------------------------------- ### Configure and Call GetPosts API Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Example of how to call the getPosts API with various parameters, including preview mode, pagination, and exclusion of the post body. It also shows how to handle the response or any errors. ```swift import ButterCMSSDK var butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getPosts(parameters: [ .preview(value: 1), .excludeBody, .page(value: 1), .pageSize(value: 10) ]) { result in switch result { case .success(let posts): //Do something on success print("Count: \(posts.meta.count)") posts.data.compactMap() { print("Post: \($0.title)") } case .failure(let error): //Do something on failure print("getPost failed with Error: \(error)") } } ``` -------------------------------- ### Search Blog Posts by Query Source: https://context7.com/buttercms/buttercms-swift/llms.txt Searches for blog posts using a provided query string, with options for pagination. The example shows how to handle search results, printing the count of matching posts and their titles and summaries. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.searchPosts(parameters: [ .query(value: "Swift development"), .page(value: 1), .pageSize(value: 5) ]) { result in switch result { case .success(let posts): print("Found (posts.meta.count) matching posts") for post in posts.data { print("Title: (post.title)") print("Summary: (post.summary ?? "")") } case .failure(let error): print("Error searching posts: (error.localizedDescription)") } } ``` -------------------------------- ### Retrieve Blog Posts with Parameters Source: https://context7.com/buttercms/buttercms-swift/llms.txt Fetches a list of blog posts with support for pagination, filtering by author, category, and tag, and excluding the post body. The example shows how to handle success and failure responses, printing metadata and post details. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getPosts(parameters: [ .preview(value: 1), .excludeBody, .page(value: 1), .pageSize(value: 10), .authorSlug(value: "john-doe"), .categorySlug(value: "tutorials"), .tagSlug(value: "swift") ]) { result in switch result { case .success(let posts): print("Total posts: (posts.meta.count)") print("Next page: (posts.meta.nextPage ?? 0)") print("Previous page: (posts.meta.previousPage ?? 0)") for post in posts.data { print("Title: (post.title)") print("Slug: (post.slug)") print("Summary: (post.summary ?? "")") print("Featured Image: (post.featuredImage ?? "")") print("Author: (post.author?.firstName ?? "") (post.author?.lastName ?? "")") print("Published: (post.published ?? Date())") if let categories = post.categories { print("Categories: (categories.map { $0.name }.joined(separator: ", "))") } if let tags = post.tags { print("Tags: (tags.map { $0.name }.joined(separator: ", "))") } } case .failure(let error): print("Error fetching posts: (error.localizedDescription)") } } ``` -------------------------------- ### Retrieve Single Blog Post by Slug Source: https://context7.com/buttercms/buttercms-swift/llms.txt Fetches a specific blog post using its unique slug. The example demonstrates accessing post details such as title, body, SEO information, and URL. It also shows how to retrieve the previous and next posts in the sequence. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getPost(slug: "my-first-blog-post") { result in switch result { case .success(let response): let post = response.data print("Title: (post.title)") print("Body: (post.body ?? "")") print("SEO Title: (post.seoTitle ?? "")") print("Meta Description: (post.metaDescription ?? "")") print("URL: (post.url ?? "")") print("Status: (post.status?.rawValue ?? "")") // Access previous and next posts if let previousPost = response.meta.previousPost { print("Previous: (previousPost.title)") } if let nextPost = response.meta.nextPost { print("Next: (nextPost.title)") } case .failure(let error): print("Error fetching post: (error.localizedDescription)") } } ``` -------------------------------- ### Retrieve Tags using ButterCMS SDK in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt Demonstrates fetching single or all tags from ButterCMS via the Swift SDK, with an option to include recent posts for each tag. The code shows how to get a specific tag by its slug and list all tags. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // Get single tag butter.getTag(slug: "swift", parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let response): let tag = response.data print("Tag: \(tag.name)") print("Slug: \(tag.slug)") if let recentPosts = tag.recentPosts { print("Recent posts with this tag:") for post in recentPosts { print(" - \(post.title)") } } case .failure(let error): print("Error fetching tag: \(error.localizedDescription)") } } // Get all tags butter.getTags(parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let tags): for tag in tags.data { print("Tag: \(tag.name) (\(tag.slug))") } case .failure(let error): print("Error fetching tags: \(error.localizedDescription)") } } ``` -------------------------------- ### Define Posts Parameters Enum Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md An example Swift enum defining available parameters for the Posts API. This enum helps in strongly typing API requests and leverages Xcode's autocompletion. ```swift public enum PostsParameters: Parameters { case preview(value: Int) case page(value: Int) case pageSize(value: Int) case excludeBody case authorSlug(value: String) case categorySlug(value: String) case tagSlug(value: String) } ``` -------------------------------- ### Override Preview Mode Settings Source: https://context7.com/buttercms/buttercms-swift/llms.txt Shows how to manage preview mode settings both globally when initializing the ButterCMSClient and per-API call basis. Preview mode allows accessing draft and scheduled content. The example demonstrates enabling preview globally, disabling it for specific calls, and changing the global setting after initialization. Useful for development vs production environments and content management workflows. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY", previewMode: true) // This call will use preview mode (global setting) butter.getPosts(parameters: [.page(value: 1)]) { result in // Handles draft/scheduled posts } // Override to disable preview for this specific call butter.getPosts(parameters: [ .preview(value: 0), .page(value: 1), .pageSize(value: 10) ]) { result in // Only published posts returned } // Change global setting butter.previewMode = false // Now all subsequent calls will not use preview by default butter.getPosts(parameters: [.page(value: 1)]) { result in // Only published posts } ``` -------------------------------- ### Retrieve Collections with Custom Schemas Source: https://context7.com/buttercms/buttercms-swift/llms.txt Demonstrates how to define custom collection items by implementing the CollectionItem protocol and fetching collections with various parameters including locale, pagination, ordering, and field filtering. The example shows a FAQ collection with multiple properties and proper JSON decoding. Dependencies include ButterCMSSDK framework and valid API key. Supports advanced querying with multiple parameters and typed responses. ```swift import ButterCMSSDK // Define collection item as a class implementing CollectionItem private class FaqItem: CollectionItem { var meta: CollectionItemMeta var question: String = "" var answer: String = "" var category: String = "" var displayOrder: Int = 0 required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) meta = try container.decode(CollectionItemMeta.self, forKey: .meta) question = try container.decode(String.self, forKey: .question) answer = try container.decode(String.self, forKey: .answer) category = try container.decodeIfPresent(String.self, forKey: .category) ?? "" displayOrder = try container.decodeIfPresent(Int.self, forKey: .displayOrder) ?? 0 } private enum CodingKeys: String, CodingKey { case meta, question, answer, category, displayOrder } } let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getCollection( slug: "faq", parameters: [ .locale(value: "en"), .page(value: 1), .pageSize(value: 20), .order(by: "displayOrder", direction: .asc), .fields(name: "category", value: "general") ], type: FaqItem.self ) { result in switch result { case .success(let collection): print("Total items: \(collection.meta.count)") for item in collection.data.items { print("ID: \(item.meta.id)") print("Question: \(item.question)") print("Answer: \(item.answer)") print("Category: \(item.category)") print("---") } case .failure(let error): print("Error fetching collection: \(error.localizedDescription)") } } ``` -------------------------------- ### Retrieve Categories using ButterCMS SDK in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt Fetches single or multiple categories from ButterCMS using the Swift SDK. This includes an example of including recent posts associated with a category and retrieving all available categories. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // Get single category butter.getCategory(slug: "tutorials", parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let response): let category = response.data print("Category: \(category.name)") print("Slug: \(category.slug)") if let recentPosts = category.recentPosts { print("Recent posts in category:") for post in recentPosts { print(" - \(post.title)") } } case .failure(let error): print("Error fetching category: \(error.localizedDescription)") } } // Get all categories butter.getCategories(parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let categories): for category in categories.data { print("Category: \(category.name) (\(category.slug))") } case .failure(let error): print("Error fetching categories: \(error.localizedDescription)") } } ``` -------------------------------- ### Retrieve RSS and Atom Feeds using ButterCMS SDK in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt Fetches RSS or Atom feeds from ButterCMS using the Swift SDK. Examples include retrieving a general RSS feed, a feed filtered by category slug, and an Atom feed filtered by tag slug. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // Get RSS feed butter.getFeeds(name: "rss") { result in switch result { case .success(let feed): print("Feed data: \(feed.data)") case .failure(let error): print("Error fetching feed: \(error.localizedDescription)") } } // Get filtered feed by category butter.getFeeds(name: "rss", parameters: [ .categorySlug(value: "tutorials") ]) { result in switch result { case .success(let feed): print("Filtered feed: \(feed.data)") case .failure(let error): print("Error fetching feed: \(error.localizedDescription)") } } // Get filtered feed by tag butter.getFeeds(name: "atom", parameters: [ .tagSlug(value: "swift") ]) { result in switch result { case .success(let feed): print("Atom feed: \(feed.data)") case .failure(let error): print("Error fetching feed: \(error.localizedDescription)") } } ``` -------------------------------- ### Handle Error Scenarios and API Responses Source: https://context7.com/buttercms/buttercms-swift/llms.txt Comprehensive example of error handling patterns for ButterCMS API calls using Swift's Result type. Demonstrates handling different ButterCMSError types including no data returned, invalid HTTP responses, server errors with status codes, and JSON decoding failures. Includes specific handling for common HTTP status codes (401, 404, 429) and network errors. Essential for production applications requiring robust error management and user feedback. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getPosts(parameters: [.page(value: 1)]) { result in switch result { case .success(let posts): // Process successful response print("Successfully fetched \(posts.data.count) posts") case .failure(let error): // Handle different error types if let butterError = error as? ButterCMSError { switch butterError.error { case .noDataReturned: print("No data returned from API") case .responseNotHTTPURLResponse: print("Invalid response type") case .serverResponseNotOK(let statusCode): print("Server error with status code: \(statusCode)") if statusCode == 401 { print("Authentication failed - check API key") } else if statusCode == 404 { print("Resource not found") } else if statusCode == 429 { print("Rate limit exceeded") } case .canNotDecodeData(let data): print("Failed to decode response data") if let jsonString = String(data: data, encoding: .utf8) { print("Raw response: \(jsonString)") } } } else { // Handle network errors print("Network error: \(error.localizedDescription)") } } } ``` -------------------------------- ### Retrieve Pages with Nested Objects in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt This Swift example handles complex page schemas with nested Codable structs from ButterCMSSDK. It depends on an API key and supports filters like fields for nested properties. Outputs page names and nested hero data, managing success and error scenarios. ```swift import ButterCMSSDK // Define nested structures private struct Hero: Codable { var firstname: String var lastname: String var image: String var bio: String } private struct HeroPageFields: Codable { var hero: Hero var subtitle: String var backgroundImage: String } let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.getPages( parameters: [ .locale(value: "en"), .preview(value: 1), .fields(key: "hero.firstname", value: "Peter"), .fields(key: "hero.lastname", value: "Pan"), .levels(value: 1), .order(value: "updated") ], pageTypeSlug: "hero_page", type: HeroPageFields.self ) { result in switch result { case .success(let pages): for page in pages.data { print("Page: \(page.name)") print("Hero: \(page.fields.hero.firstname) \(page.fields.hero.lastname)") print("Bio: \(page.fields.hero.bio)") print("Subtitle: \(page.fields.subtitle)") } case .failure(let error): print("Error fetching pages: \(error.localizedDescription)") } } ``` -------------------------------- ### Instantiate ButterCMS Client Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Demonstrates how to initialize the ButterCMSClient with an API key. It also shows how to provide a custom URLSession configuration or enable preview mode. ```swift import ButterCMSSDK var butter = ButterCMSClient(apiKey: "YOUR_API_KEY") ``` ```swift import ButterCMSSDK var butter = ButterCMSClient(apiKey: "YOUR_API_KEY", urlSession: yourURLSession) ``` ```swift import ButterCMSSDK var butter = ButterCMSClient(apiKey: "YOUR_API_KEY", previewMode=true) ``` -------------------------------- ### Initialize ButterCMS Client Source: https://context7.com/buttercms/buttercms-swift/llms.txt Demonstrates how to initialize the ButterCMS client with an API key. It shows basic initialization, initialization with a custom URLSession, and enabling global preview mode. The preview mode can also be changed after initialization. ```swift import ButterCMSSDK // Basic initialization let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // With custom URLSession let customSession = URLSession(configuration: .default) let butter = ButterCMSClient(apiKey: "YOUR_API_KEY", urlSession: customSession) // With preview mode enabled globally let butter = ButterCMSClient(apiKey: "YOUR_API_KEY", previewMode: true) // Change preview mode later butter.previewMode = false ``` -------------------------------- ### Data Model Definitions for ButterCMS Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Data model definitions for ButterCMS pages and collections. CaseStudyPageFields implements Codable for page schema modeling, while FaqItem implements CollectionItem protocol for collection item modeling with required meta property and custom fields. ```swift private struct CaseStudyPageFields: Codable { var title: String var content: String var industry: String var subindustry: String var featuredImage: String var reviewer: String var studyDate: Date } private class FaqItem: CollectionItem { var meta: CollectionItemMeta var question: String = "" var answer: String = "" } ``` -------------------------------- ### Toggle Preview Mode Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Demonstrates how to override the global preview mode setting for a specific API call or change it on the client instance level after initialization. ```swift butter.getPosts(parameters: [ .preview(value: 0)]) { result in .... } ``` ```swift butter.previewMode = false ``` -------------------------------- ### Search Pages in ButterCMS with Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt This Swift code searches pages using query strings and filters via ButterCMSSDK. It requires an API key and allows parameters like page type, locale, and pagination. Outputs matching page details including title, industry, and content preview, with error handling. ```swift import ButterCMSSDK private struct CaseStudyPageFields: Codable { var title: String var content: String var industry: String var subindustry: String var featuredImage: String var reviewer: String var studyDate: Date } let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") butter.searchPages( parameters: [ .query(value: "Automotive"), .pageType(value: "case_studies"), .locale(value: "en"), .page(value: 1), .pageSize(value: 10), .preview(value: 1) ], type: CaseStudyPageFields.self ) { result in switch result { case .success(let pages): print("Found \(pages.meta.count) matching pages") for page in pages.data { print("Title: \(page.fields.title)") print("Industry: \(page.fields.industry)") print("Subindustry: \(page.fields.subindustry)") print("Reviewer: \(page.fields.reviewer)") print("Study Date: \(page.fields.studyDate)") print("Content preview: \(String(page.fields.content.prefix(100)))") } case .failure(let error): print("Error searching pages: \(error.localizedDescription)") } } ``` -------------------------------- ### ButterCMS Pages API Method Declarations Source: https://github.com/buttercms/buttercms-swift/blob/master/README.md Core method signatures for ButterCMS Pages API including getPage, searchPages, and getPages methods. These generic methods accept Decodable types for type-safe page data deserialization with completion handlers returning Result types. ```swift getPage(slug: String, parameters: [PageParameters] = [], pageTypeSlug: String, type: T.Type, completion: @escaping (Result, Error>) -> Void) public func searchPages(parameters: [PageSearchParameters], type: T.Type, completion: @escaping (Result, Error>) -> Void) getPages(parameters: [PagesParameters] = [], pageTypeSlug: String, type: T.Type, completion: @escaping (Result, Error>) -> Void) ``` -------------------------------- ### Retrieve Pages with Custom Schema in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt This Swift code fetches pages with custom field schemas using Codable structs from ButterCMSSDK. It requires an API key and handles parameters like preview, locale, and levels for retrieving single or multiple pages. Outputs include page metadata and custom fields, with error handling for failures. ```swift import ButterCMSSDK // Define your page schema as a Codable struct private struct LandingPageFields: Codable { var title: String var headline: String var heroImage: String var description: String var ctaText: String var ctaUrl: String } let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // Get single page butter.getPage( slug: "home-page", parameters: [ .preview(value: 1), .locale(value: "en"), .levels(value: 2) ], pageTypeSlug: "landing_page", type: LandingPageFields.self ) { result in switch result { case .success(let response): let page = response.data print("Page Name: \(page.name)") print("Status: \(page.status?.rawValue ?? "")") print("Published: \(page.published ?? Date())") // Access custom fields print("Title: \(page.fields.title)") print("Headline: \(page.fields.headline)") print("Hero Image: \(page.fields.heroImage)") print("Description: \(page.fields.description)") print("CTA: \(page.fields.ctaText) -> \(page.fields.ctaUrl)") case .failure(let error): print("Error fetching page: \(error.localizedDescription)") } } // Get multiple pages of same type butter.getPages( parameters: [ .locale(value: "en"), .page(value: 1), .pageSize(value: 10), .order(value: "updated") ], pageTypeSlug: "landing_page", type: LandingPageFields.self ) { result in switch result { case .success(let pages): print("Total pages: \(pages.meta.count)") for page in pages.data { print("Page: \(page.name)") print(" Title: \(page.fields.title)") print(" Headline: \(page.fields.headline)") } case .failure(let error): print("Error fetching pages: \(error.localizedDescription)") } } ``` -------------------------------- ### Retrieve Authors using ButterCMS SDK in Swift Source: https://context7.com/buttercms/buttercms-swift/llms.txt Fetches single or multiple authors from ButterCMS using the Swift SDK. It demonstrates how to include related posts for an author and retrieve a list of all authors. ```swift import ButterCMSSDK let butter = ButterCMSClient(apiKey: "YOUR_API_KEY") // Get single author butter.getAuthor(slug: "john-doe", parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let response): let author = response.data print("Name: \(author.firstName ?? "") \(author.lastName ?? "")") print("Email: \(author.email ?? "")") print("Bio: \(author.bio ?? "")") print("Title: \(author.title ?? "")") print("LinkedIn: \(author.linkedinUrl ?? "")") print("Twitter: \(author.twitterHandle ?? "")") print("Profile Image: \(author.profileImage ?? "")") if let recentPosts = author.recentPosts { print("Recent posts by author:") for post in recentPosts { print(" - \(post.title)") } } case .failure(let error): print("Error fetching author: \(error.localizedDescription)") } } // Get all authors butter.getAuthors(parameters: [ .include(value: "recent_posts") ]) { result in switch result { case .success(let authors): for author in authors.data { print("Author: \(author.firstName ?? "") \(author.lastName ?? "") (\(author.slug))") } case .failure(let error): print("Error fetching authors: \(error.localizedDescription)") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.