Skip to content

contentstack/contentstack-ios-graphql-example

Repository files navigation

Build an example app using Contentstack GraphQL API, and Apollo Client

We have created a sample product catalog app that is built using Apollo Client iOS SDK. The content of this app is powered by Contentstack GraphQL APIs, and the app uses Apollo client on the client side to consume GraphQL APIs.

This document covers the steps to get this app up and running for you. Try out the app and play with it, before building bigger and better applications.

Prerequisite

Step 1: Create a stack

Log in to your Contentstack account, and create a new stack. Read more about stack.

Step 2: Add a publishing environment

Add a publishing environment to publish your content in Contentstack. Provide the necessary details as per your requirement. Read more about environments.

Step 3: Import content types

For this app, we need one content type: Product. Here’s what it is needed for:

  • Product: Lets you add the product content into your app.

For quick integration, we have already created the content type. Download the content types and import it to your stack. (If needed, you can create your own content types. Read more about Content Types.)

Now that all the content types are ready, let’s add some content for your Product app.

Step 4: Add content

Create and publish entries for the ‘Product’ content type.

Now that we have created the sample data, it’s time to use and configure the presentation layer.

Step 5: Clone and configure the application

To get your app up and running quickly, we have created a sample iOS app for this project. You need to download it and change the configuration. Download the app using the command given below:

$ git clone https://github.com/contentstack/contentstack-ios-graphql-example.git

Once you have downloaded the project, add your Contentstack API Key, Delivery Token, and Environment to the project during the SDK initialization step. (Learn how to find your Stack's API Key and Delivery Token. Read more about Environments.).

Open variables.xcconfig and inject your credentials so it looks like this:

CONTENTSTACK_API_KEY=<API_KEY>  
CONTENTSTACK_DELIVERY_TOKEN=<DELIVERY_TOKEN>  
CONTENTSTACK_ENVIRONMENT=<ENVIRONMENT_NAME>  
CONTENTSTACK_HOST_NAME=<HOST_NAME>

Step 6: Install Apollo framework

Install Apollo.framework into your project using Carthage, CocoaPods, or by manually integrating it with Xcode. Refer the Installation doc for more information.

Step 7: Download your schema

Download schema using Apollo CLI

Download the GraphQL schema for your content model using Apollo CLI, and place it in the root directory of your Xcode project:

apollo schema:download --endpoint="https://graphql.contentstack.com/stacks/<API_KEY>?environment=<ENVIRONMENT_NAME>" --header="access_token: <ENVIRONMENT_SPECIFIC_DELIVERY_TOKEN>"

Refer the Downloading Schema doc for more information.

Download schema using Contentstack schema download

Step 8: Write your GraphQL queries

Contentstack provides a GraphQL playground, which is a GraphiQL interface, to test your GraphQL queries in your browser. Use this interface to write and test your queries.

Open a browser of your choice and hit the URL given below:

https://www.contentstack.com/docs/developers/apis/graphql-content-delivery-api/explorer/

Now to get the list of all entries of the Product content type within the ProductListViewController.swift create a file named ProductListViewController.graphql and add the following code snippet to get.

query Products($skip: Int = 0 ,$limit: Int){
    all_product(locale:"en-us",skip:$skip,limit:$limit) {
        items {
            title
            description
            price
            featured_imageConnection (limit: 10){
                edges{
                    node {
                        ...AssetFile
                    }
                }
            }
        }
    }
}

fragment AssetFile on SysAsset {
    filename
    url
}


Note:

  • If you have pieces of data that you may want to reuse in multiple places, make use of fragments. Refer the Using fragments doc for more details.
  • Apollo iOS generates code from queries and mutations contained in .graphql files in your target.
  • A useful convention is to colocate queries, mutations, or fragments with the Swift code that uses them by creating .graphql next to .swift.

Step 9: Add a code generation build step

Once your queries are working and return the expected data, the next step is to add a code generation build step to your target by invoking Apollo as part of the Xcode build process.

Now, you need to, create a build step and make sure that it runs before ‘Compile Sources’. To do so, perform the steps given below:

  1. Click on the Build Phases settings tab under your application’s TARGETS section.
  2. Click on the ‘+’ (Plus) icon and select New Run Script Phase.
  3. Create a run script and change its name to ‘Generate Apollo GraphQL API’.
  4. Drag this script just above Compile Sources. This opens the script area. Add the following content into it:
SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts"
cd "${SRCROOT}/${TARGET_NAME}"
"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift

Now, build your project. This will generate the API.swift file in project dictionary add it to Xcode project.

Step 10: Create an Apollo client

After downloading the schema and creating the queries, create an instance of ApolloClient and point it at the GraphQL server.

To do this, define a global variable in AppDelegate.swift by using an immediately invoked closure as follows:


let apollo: ApolloClient = {  
    let url = URL(string: "https://\(credentials.domainHost)/stacks/\(credentials.apiKey)?environment=\(credentials.environmentToken)")!
    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = ["access_token": credentials.deliveryAPIAccessToken]
    return  ApolloClient(networkTransport: HTTPNetworkTransport(url: url, client: URLSessionClient(sessionConfiguration: configuration)))
}()

To know how to add additional headers to requests, and to include authentication details, refer the Adding additional headers section.

Step 11: Build application to generate Swift query models

Finally, integrate Apollo Client into your app, pass the Swift model and queries generated above, and fetch the relevant data using the following code snippet:

apollo.fetch(query: ProductsQuery(skip: skip, limit: 5)) {[weak  self] result, error in  
	guard  let resultS = result, let data = resultS.data, let products = data.allProduct?.items else {  
		return  
	}  
	for product in products {  
		print(product.title)  
	}  
}

Step 12: Build and run your application

Now that we have a working project, you can build and run it.

More Resources

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages