Blogs

Complete Integration of GraphQL in iOS Swift

Purpose of the article: Demonstrates the integration of Apollo Framework for GraphQL API consumption. Shows code snippets of the GraphQL operations.

Intended Audience: iOS developers

Tools and Technology: XCode, Swift, GraphQL, Apollo

Keywords: GraphQL, Swift, iOS, Apollo

Purpose of the article: Demonstrates the integration of Apollo Framework for GraphQL API consumption. Shows code snippets of the GraphQL operations.

Intended Audience: iOS developers

Tools and Technology: XCode, Swift, GraphQL, Apollo

Keywords: GraphQL, Swift, iOS, Apollo

What is GraphQL?

According to graphql.orgGraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

GraphQL is a query language for APIs, and we define a type system for our data to execute queries at the server-side in runtime. GraphQL is not any specific database or storage engine.

Why do we need GraphQL when we have REST APIs? 

REST is the API design architecture, which has become the common way of writing web services over the last few years. It uses HTTP to fetch data and various operations like PUT, GET, POST, DELETE in JSON format for better and faster data.

However, REST also comes with some downsides. Among which some of the most common cons are:

  • Over-Fetching: Receiving more data than needed
  • Under-Fetching: Not fetching all the required data
  • Multiple Requests: Need to wait for multiple requests to get desired resources
  • Dependent Request: A series of requests to get the required data

With GraphQL relationship, you can get the data in a single request. No more callbacks and waiting on multiple endpoint requests to resolve. Get all your data in one request. Now you avoid over-fetching, under-fetching, multiple requests, and dependent requests to get the data for the components.

With GraphQL query, we can get data back in a single request. Unlike REST API, there are no callbacks and waiting on various endpoints to resolve our problems. Get all your data in one request. By this, we do not need to call multiple requests to the server, dependent requests, and round-trip service calls to get the data for our apps. GraphQL lets developers choose what they need in the response whenever any query is executed, unlike the usual REST API calls where the app will get the entire response even if it does not need some data. GraphQL is a wrapper over the REST APIs in the background.

Implementation for GraphQL in iOS.

GraphQL allows us to execute queries and mutations over the HTTP request to the GraphQL server and returns the results specified in the query.

Apollo iOS is a GraphQL client for native iOS written in Swift.

Installation:

You can integrate apollo.framework in three different ways in your project.

  1. Swift Package Manager
  2. Cocoa Pods
  3. Carthage (We are not going to cover this in our article)

1. Swift Package Manager installation

1) Go to XCode, File > Swift Packages > Add package dependency

2) Paste the URL to the GraphQL repo on GitHub (https://github.com/apollographql/apollo-ios.git) in the search bar and click on the Next button

    3) Select the appropriate version to install. XCode will automatically suggest selecting the current version. It is strongly recommended to choose the Up to Next Major option, as there will be breaking changes in the minor version.

    4) Select which package you want to use. If you are just getting started, select the ‘Apollo’ library first; you can always come back later and add the other packages if you need them. Now click on Finish for the completion of the process.

5) It is done.

2. Cocoa Pods installation

1) Apollo iOS is written in Swift 5, select 1.7.0 or higher version of Cocoa pods. Run the following command in the terminal to install cocoa pods in your system.

~ % gem install cocoapods

2) To install the pod file in your project, type the below command in the terminal.

~ % pod init

This will generate a podfile in your project directory.

3) Open the podfile in Text Edit and add the below line below your project target name.

pod ‘Apollo’

  • If you also want to use the ApolloSQLite framework, add
    pod ‘Apollo/SQLite’
  • If you also want to use the ApolloWebSocket, add
    pod ‘Apollo/WebSocket

4) Run pod install

This will generate a ‘.xcworkspace’ file in the project directory

5) Open ‘.xcworkspace’ and start your work

At this point, the installation of Apollo in our project is almost complete. Now we need to add schema to the project

Add schema file to your project target

We have to download and add the schema file to generate the code. We will need a GraphQL schema file to generate the required Swift code. A schema file is a JSON file that contains the result of the service calls. This file calls ”schema.json”. This file needs to be added to the project folder.

Create ‘.graphql’ file with query, mutation, and subscription

Apollo iOS has a beautiful feature. It will make use of the ‘.graphql’ file in the project target which contains queries and mutations to generate the code.

Adding code generator build steps:

Code generator uses a ‘.graphql’ file to generate the API file that will help send query, mutation, and subscription and parse the cache response. To run the code-gen as part of the XCode build process, we need to add a build script before the ‘Compile Source’ step in the build phase to invoke the wrapper script.

Follow the below steps to add the code-gen script.

  1. On your application target, go to the Build Phase tab, click on the + button and select New Run Script Phase
  2. In the create run script, change the name to Generate Apollo GraphQL API
  3. Drag the new run script above the Compile Sources in the build phases list, executing it before the code compiles
  4. Add the content of the appropriate run script based on the package manager you are using

GraphQL support three different types of operations:

  • Query: to fetch data (REST API GET call)
  • Mutation: to post data (REST API POST call)
  • Subscription: Subscribe for real-time data

Let us look at these operations one by one with examples.

Before we begin writing the code, we need to configure the Apollo Client to make the requests. For this, we need to create ‘uploadingNetworkTransport’ and ‘webSocketNetworkTransport’. ‘UploadingNetworkTransport ‘is for non-subscription-based requests like query and mutation requests. WebSocketNetworkTransport is for subscription-based requests. These two ‘NetworkTransport’ will then be combined to create a ‘SplitNetworkTransport’ object which is then used to create an instance of Apollo Client.

Then create an object of Apollo Client.

Let us get back to the operations.

1. Query:

Let us look into the GraphQL Query operation. The query is used to read or fetch the values, just like a GET call in REST API. This helps in reducing the over-fetching of data. Unlike REST API this will restrict fields that should be fetched from the server. This means fewer queries and lesser traffic over the network, eventually reducing the response time. The query is about asking for the specific fields on the object.

Let us start by looking at the simple query and its result, then run it.

Here we can observe that the query contains the same shape as a result. The server knows what fields we asked for and gives us the same.

We can pass arguments to fields in the query.

We can add arguments in the inner fields as well, like the code below. This avoids calling multiple API calls like in REST.

Until now, we saw the queries without the keyword query and the operation name. It is helpful to make use of these to make the code more readable and meaningful. The below snippet will show you the query with the operation name.

In Swift, the above fetch query string can be used by calling the below code.

So far, we have passed the parameters inside the query. We can pass dynamic parameters to the query to get specific data. The above example will let us get all the movies. If we want to get a particular movie detail, we can pass the movie name dynamically.

The above fetch query string uses an input argument “name”. In Swift, we need to pass the argument movieName to the query to fetch the data.

2. Mutation:

Now let us look into GraphQL Mutation operation. The mutation can send or modify server-side data. This is just like a POST call in REST API. Mutation operation is just similar to query operation. You can observe that the mutation syntax is the same as the query except for the keyword. Just replace the keyword from query to mutation and you are done.

Just like a query you can ask for nested data on successful mutation operation. The mutation performs two operations in one query string.

1. First it will do the server-side operation.

2. Second it returns the data we asked for.

3. Subscription:

Now let us look into GraphQL Subscription operation. Subscription is used to get the updated result whenever there is a change in the server-side data. Mostly the updated data is pushed from the server to the subscribing client. Subscription is basically used for real-time updates just like a chat application. A graphql subscription is a subscription query string sent to the web-socket endpoint. And whenever data change in the backend, the new data is pushed over the web-socket from the server to the client.

Subscription uses ApolloWebSocket frameworks to provide real-time updates from the server. Below is an example of the subscription query string.

        

The above subscription query string will subscribe for a channel to get the users who are currently online. Below Swift code will subscribe to get current live users who are online now.

The function “subscribeForOnlineUsers” will subscribe in apollo to receive live updates of the users who are currently online or active. The result needs to be handled in DispatchQueue If the result is used to update any UI. If you no more want to receive the live update you need to cancel the subscription. The function “unsubscribeForOnlineUsers” will cancel the subscription by calling the cancel property of the cancellable variable.

Conclusion:

Now that you know everything about GraphQL and its implementation with Swift. We have written queries that are very easy to understand and interpret. Apollo generates the necessary code for you in the Swift API file, then you called your queries via the Swift API code to get your work done. GraphQL is a modern way of communicating with servers that replaces the commonly used REST API calling.

Leave A Comment

Related Post

Making the Web Accessible

Purpose of the Article: How to create a custom Vue component and publish it as an npm package Intended Audience: Frontend Developers(Vuejs) Tools and Technology:

Read More »