Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstration of fetching data from React Native AsyncLocalStorage
// Since AsyncLocalStorage API is not exposed to native code, we have to grab the data ourselves.
// If you have been able to get Cocoapods use_frameworks! to work, you can `import React`
// Else make sure to include the following in your brindging header:
// #import <React/RCTAsyncLocalStorage.h>
import Foundation
class CacheManager {
let storageLocation = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("RCTAsyncLocalStorage_V1")
/// Smaller values are stored in the manifest file.
/// Larger values get written to a separate file.
lazy var manifest: [String: String]? = {
do {
let manifestLocation = storageLocation.appendingPathComponent("manifest.json")
let manifestString = try String(contentsOf: manifestLocation)
let manifestData = manifestString.data(using: .utf8)!
let manifestJSON = try JSONSerialization.jsonObject(with: manifestData, options: .allowFragments)
return manifestJSON as? [String: String]
} catch {
print(error)
return nil
}
}()
/// Grabs data given the cacheKey.
/// Looks in manifest first, then looks to the filesystem.
/// If we find a string, we attempt to convert it to JSON.
func fetch(cacheKey: String) -> Any? {
var jsonString: String?
if let value = manifest?[cacheKey] {
jsonString = value
} else {
let fileName = RCTMD5Hash(cacheKey)
let fileLocation = storageLocation.appendingPathComponent(fileName)
jsonString = try? String(contentsOf: fileLocation)
}
guard jsonString != nil else {
return nil
}
do {
let jsonData = jsonString!.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
return json
} catch {
print(error)
return jsonString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.