Apollo Client in iOS and Android
How to use Apollo Client in iOS and Android
Foreword: This is a record about my outside project
Download library
iOS Cocoapods : pod ‘Apollo’
Android Gradle:
Set in build.gradle(Project):
buildscript {
ext.kotlin_version = "1.4.21"
ext.apollo_version = "2.5.2"
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath("com.apollographql.apollo:apollo-gradle-plugin:$apollo_version")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
Set in build.gradle(Module):
plugins {
id 'com.apollographql.apollo'
}
Add this to generate Kotlin models;
apollo {
// instruct the compiler to generate Kotlin models
generateKotlinModels.set(true)
}
Then set implementation:
dependencies {
// Apollo
implementation("com.apollographql.apollo:apollo-runtime:$apollo_version")
implementation("com.apollographql.apollo:apollo-coroutines-support:$apollo_version")
}
Download Schema.json
iOS:
Set Build Phase like below picture:
Put below code in shell:
SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts"
cd "${SRCROOT}/${TARGET_NAME}"
"${SCRIPT_PATH}"/run-bundled-codegen.sh schema:download --endpoint=http://your_graphiql_schema_domain schema.json
This domain can show this on browser:
Android:
Please create graphql folder like below and don’t change name and location. If you change it, Apollo won’t find the file
Add .graphql file:
I use official web side directly, because iOS an Android are all the same
Link: https://www.apollographql.com/docs/android/essentials/get-started-kotlin/
Generate Graphql Model:
iOS:
Change shell to this and then clean build, and then they’ll in API.swift file
SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts"
cd "${SRCROOT}/${TARGET_NAME}"
"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql
Android:
Clean build directly and you will see in below:
Set ApolloClient:
iOS
class ApolloService: NSObject {
static let shared = ApolloService()
private(set) lazy var apollo = ApolloClient(url: URL(string: "http://your_api_domain/api")!)
}
Android
val apolloClient: ApolloClient = ApolloClient.builder()
.serverUrl("http://your_api_domain/api")
.build()
Mutation and Query:
iOS
Mutation
let service = ApolloService.shared.apollo
let mutation = ApolloMutation(params: String)
service.perform(mutation: mutation){ result in
switch result {
case .success(let gqlResult):
if gqlResult.errors != nil {
status = .Failed
} else {
status = .Success
responseData = gqlResult.data?.apolloMutation
}
case .failure(let error):
print(error.localizedDescription)
action.status = .Failed
}
}
Query
let service = ApolloService.shared.apollo
let query = ApolloQuery(params: String)
service.fetch(query: query) { result in
switch result {
case .success(let graphQLResult):
if graphQLResult.errors != nil {
print(graphQLResult.errors?.description ?? "")
status = .Failed
return
}
if graphQLResult.data?.apolloQuery != nil {
status = .Success
action.responseData = graphQLResult.data?.apolloQuery
} else {
action.status = .Failed
}
case .failure(let error):
print(error.localizedDescription)
status = .Failed
}
}
Android
Mutation
val mutation = ApolloMutation(params = "params")
apolloClient.mutate(mutation).enqueue(
object : ApolloCall.Callback<ApolloMutation.Data>() {
override fun onResponse(
response: Response<ApolloMutation.Data>) {
responseData = response.data?.apolloMutation
status = NetWorkStatus.SUCCESS
}
override fun onFailure(e: ApolloException) {
status = NetWorkStatus.FAILED
}
})
Query
CoroutineScope(Dispatchers.IO).launch {
val response =
apolloClient.query(ApolloQuery(
params = "params"
)).await()
withContext(Dispatchers.Main){
when {
response.hasErrors() -> {
status = NetWorkStatus.FAILED
}
else -> {
action.responseData = response.data?.apolloQuery
action.status = NetWorkStatus.SUCCESS
}
}
}
}
Happy coding !!