Setup 4/29/2020

I’m using Xcode 11 , Apollo 0.25.0, and SDWebImageSwiftUI 1.3.3.

If you just want to go straight to the code, then you can clone the project:

Get Yelp API info

You will need to create an account with Yelp and then navigate to the developer portal and generate a Client ID and API Key for your “App.”

Set up Xcode project

Make a new single app Xcode project and use SwiftUI. For code generation to work, you will need a folder called GraphQL . You will need two files in this folder. First, create the businesses.graphql file by adding an “Empty” file and then make a file called API.siwft . This latter file will be generated later on, but it won’t be part of the project unless you add it here or drag it into the project later after it’s generated.

The code generation will need the businesses.graphql file to do its work, so add our GraphQL query to that file:

You can repeat this pattern for other queries, but this is all we need for this demo. I used this documentation to write the GraphQL query.

Add code generation

I’m using Apollo’s beta code generation tool. Their official documentation can be found at this link, but I’m just going to give you a condensed walkthrough.

We will be making a Swift package that can run scripts we write in Swift. Cool! We will wire up our actual app to invoke that script. I follow the Apollo documentation and save this package in the same directory as the Xcode project under the folder Codegen .

You can set up the code generation Swift package from the terminal. In your terminal, cd to the Xcode project directory and mkdir Codegen . Then cd Codegen/ . Once you are in your new directory, run swift package init --type executable to make a new Swift package.

You will need to modify the Package.swift file to look like this:

Then add this code to your main.swift file:

If you look through the comments in the code, you can see we are able to get a reference to the Xcode project’s GraphQL folder we created first. There, we introspect the schema.json file and generate the API.swift file. You can run this Swift package from the command line by typing swift run .

We will finish the code generation setup by adding a “build script” phase in the Xcode project. Make sure the script is right after the Dependencies.

cd "${SRCROOT}"/Codegen xcrun -sdk macosx swift run