Using RCTAsyncLocalStorage + getAllKeys

2019-03-04 00:10发布

问题:

I'm trying to get the AsyncStorage on iOS native code. So this is my code

- (void)jsonFromLocalRNStrogeForKey:(NSString *)key completion:(void (^)(NSDictionary * _Nullable, NSError * _Nullable))completion {
    RCTResponseSenderBlock rnCompletion = ^(NSArray *response) {

        NSString *jsonAsString;

        if (response.count > 1) {
            NSArray *response1 = response[1];
            if (response1.count > 0) {
                NSArray *response2 = response1[0];
                if (response2.count > 1) {
                    jsonAsString = response2[1];
                }
            }
        }

        @try {
            NSData *jsonAsData = [jsonAsString dataUsingEncoding:NSUTF8StringEncoding];

            NSError *error;

            NSDictionary *json = [
              NSJSONSerialization
              JSONObjectWithData:jsonAsData
              options:NSJSONReadingMutableContainers
              error:&error
            ];

            completion(json, error);
        }
        @catch (NSException *exception) {
            NSLog(@"error: %@", exception.reason);

            NSMutableDictionary * info = [NSMutableDictionary dictionary];
            [info setValue:exception.name forKey:@"ExceptionName"];
            [info setValue:exception.reason forKey:@"ExceptionReason"];
            [info setValue:exception.callStackReturnAddresses forKey:@"ExceptionCallStackReturnAddresses"];
            [info setValue:exception.callStackSymbols forKey:@"ExceptionCallStackSymbols"];
            [info setValue:exception.userInfo forKey:@"ExceptionUserInfo"];

            NSError *error = [[NSError alloc] initWithDomain:@"" code:1 userInfo:info];

            completion(nil, error);
        }
    };

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

    dispatch_async(storage.methodQueue, ^{
        @try {
            // [storage performSelector:@selector(multiGet:callback:) withObject:@[key] withObject:rnCompletion];
            [storage performSelector:@selector(getAllKeys:callback:) withObject:rnCompletion];
        }
        @catch (NSException *exception) {
            NSLog(@"error: %@", exception.reason);
        }
    });
}

When I try to get one of my keys (multiGet)

[self jsonFromLocalRNStrogeForKey:@"session" completion:^(NSDictionary* data,NSError* error) {
    if (data) {
        NSString * name = [data valueForKeyPath: @"token"];
        if (![name isKindOfClass:[NSNull class]]) {
            [self reportIncomingCallFrom:name withUUID:callInvite.uuid];
        }
    } else {
        NSLog(@"error: JSON Parsing Error: %@",error.localizedFailureReason);
    }
}];

I'm always getting null

And when I try to get all the keys (...@selector(getAllKeys:...) to see what do I have in my AsyncStorage I got the exception

@"NSInvalidArgumentException" - reason: @"-[RCTAsyncLocalStorage getAllKeys:callback:]: unrecognized selector sent to instance 0x1085512c0"

The RN have RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback) in RCTAsyncLocalStorage.m; but at RCTAsyncLocalStorage.h (void)getAllKeys:(RCTResponseSenderBlock)callback it doesn't exists and even adding it doesn't work (https://github.com/facebook/react-native/blob/master/React/Modules/RCTAsyncLocalStorage.h).


"react-native": "^0.48.4",

How can I return NSJsonSerialization

回答1:

Firstly,

The RN have RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback) in RCTAsyncLocalStorage.m; but at RCTAsyncLocalStorage.h (void)getAllKeys:(RCTResponseSenderBlock)callback it doesn't exists

In Objective-C, you can invoke a method even though it is not declared in the header file using performSelector:withObject:.

Invoking this method directly (without first checking if the target respondsToSelector:) is bad practice, as the internal method declaration may change.

Secondly, this line is incorrect:

[storage performSelector:@selector(getAllKeys:callback:) withObject:rnCompletion];

Here, you're saying getAllKeys:: takes two arguments, however the implementation declares only one.

Hence, the correct way to extract all keys is the following:

dispatch_async(storage.methodQueue, ^{

    if([storage respondsToSelector:@selector(getAllKeys:)]){
        [storage performSelector:@selector(getAllKeys:) withObject:[^(NSArray* response){
            NSLog(@"Contents: %@",response);
        } copy]];
    }else{
        NSLog(@"storage does not respond to selector `getAllKeys:`");
    }

});