Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access data stored in AsyncStorage from ios native code (objective c)

I need to access data stored in AsyncStorage from iOS native Objective C code.

This is needed to get the data in sync instead of sending App event to JS and then send it back to native code.

like image 798
Prasad Sawant Avatar asked Oct 17 '16 16:10

Prasad Sawant


People also ask

Where does AsyncStorage save data React Native?

On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

Can you store object in AsyncStorage in React Native?

It allows you to use data in offline mode in React Native apps. As the name suggests AsyncStorage is asynchronous and unencrypted. As we all know asynchronous means concurrently running tasks. AsyncStorage only accepts and stores string data, so in order to store object data or value we need to use JSON.

How much data can be store in AsyncStorage in React Native?

Motivation​ Current Async Storage's size is set to 6MB. Going over this limit causes database or disk is full error. This 6MB limit is a sane limit to protect the user from the app storing too much data in the database.


1 Answers

I've just been faced with the same problem.

My solution was to move the code native side.

On iOS:

#import <React/RCTAsyncLocalStorage.h>
#import <React/RCTBridgeModule.h>

RCTResponseSenderBlock completion = ^(NSArray *response) {
  NSString *theme = response[1][0][0][1];

  // Setup RCTRootView with initialProperties
};

RCTAsyncLocalStorage *storage = [[RCTAsyncLocalStorage alloc] init];

dispatch_async(storage.methodQueue, ^{
  [storage performSelector:@selector(multiGet:callback:) withObject:@[@"theme"] withObject:completion];
});

You could additionally use dispatch_semaphore_wait to perform this synchronously

Update:

I needed the variable in the global state not just in the component props so the above doesn't go far enough.

I've had to work this into the React Native source at the point that the Javascript source is loaded.

NSString *javascriptPrepend = [NSString stringWithFormat:@"var ThemeMode = '%@';", self.theme];
NSMutableData *prependData = [[javascriptPrepend dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[prependData appendData:sourceCode];

sourceCode = prependData; 

I'll see if they're open to a PR to allow this kind of functionality and post back here if I get it through.

like image 200
Luke Rhodes Avatar answered Oct 03 '22 19:10

Luke Rhodes