Apollo-ios: Persist Cache for Offline Use?

Created on 27 Jul 2018  Â·  9Comments  Â·  Source: apollographql/apollo-ios

Is there a way to persist the cache to a local store? The project I am working on basically needs to store the user's info queried from the server and save it even when the app is force closed and re-opened.

I cannot seem to find anything that would do this.

Would I be able to do a work around and create a Core Data model? How could I go about doing this?

Most helpful comment

@shaps80 I had a chance to test it today, and I did get it working. Thank you @Ded77 and @qalvapps for the solution.

All 9 comments

I've started using Apollo in an app last week and have the same question, I haven't found anything built into Apollo so far – so I'm keen on an answer to this also :)

Maybe you can use SQLiteNormalizedCache when you initialize your ApolloClient.

let cacheURL = …
let cache = try! SQLiteNormalizedCache(fileURL: cacheURL)
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: …, store: store)

Tried using it, including store.cacheKeyForObject = { $0["id"] }
Then switched off wifi and restarted the app, but I don't get any data – just an offline error.
@Ded77 is there more that I'm supposed to implement.

as per @Ded77 's comment :

let path = { path to documents directory (example) }
let cache = try! SQLiteNormalizedCache(fileURL: URL(string: "(path)/db.sqlite3")!)
let store = ApolloStore(cache: cache)
store.cacheKeyForObject = { $0["id"] }

let apolloClient = ApolloClient(networkTransport: transport, store: store)

then your fetches choose relevant cachepolicy eg : a cachePolicy of .returnCacheDataElseFetch

Yeah that's what I did. I'll play around with this a little more, perhaps I had a typo regarding on the cachePolicy. It _was_ late 😬

Thanks for getting back to me @Ded77 and @qalvapps

@shaps80 Did you get this working?

Sorry haven't had a chance to test it properly yet. Will do next week and will update. 😬

@shaps80 I had a chance to test it today, and I did get it working. Thank you @Ded77 and @qalvapps for the solution.

In this line of SQLiteNormalizedCache, what if someone is using a Json Custom Scalar field?
Also return fieldJSONValue ?
Then you can use your data as Array?
https://github.com/apollographql/apollo-ios/blob/4f35f046925d6d89ea0faba39e2e0cd028828033/Sources/ApolloSQLite/SQLiteNormalizedCache.swift#L141

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wnagrodzki picture wnagrodzki  Â·  4Comments

marcoreni picture marcoreni  Â·  3Comments

plm75 picture plm75  Â·  4Comments

Dmurph24 picture Dmurph24  Â·  4Comments

Robuske picture Robuske  Â·  3Comments