Skip to content

Instantly share code, notes, and snippets.

@christianchown
Created April 25, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianchown/a2d2a6db02cb3149eec304a3712f5d8b to your computer and use it in GitHub Desktop.
Save christianchown/a2d2a6db02cb3149eec304a3712f5d8b to your computer and use it in GitHub Desktop.
React Native iOS NativeModule to read a plist as a string
//
// ReadPlist.m
//
#import <UIKit/UIKit.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTUtils.h>
#import <Foundation/NSData.h>
#import <Foundation/Foundation.h>
@interface ReadPlist : NSObject <RCTBridgeModule>
@end
@implementation ReadPlist
RCT_EXPORT_MODULE();
/*
// Usage:
const reader = React.NativeModules.ReadPlist;
reader.readRawPlist(path, (error, contents) => {});
// or
const contents = await reader.readRawPlistPromise(path);
*/
#pragma mark - read raw plist
RCT_EXPORT_METHOD(readRawPlist:(NSString *)localPath :(RCTResponseSenderBlock)callback){
NSString *asString = [self getPlistAsString:localPath];
callback(@[[NSNull null], asString]);
}
#pragma mark - promisified read raw plist
RCT_REMAP_METHOD(readRawPlistPromise,
localPath:(NSString *)localPath
resolver:(RCTPromiseResolveBlock)resolve
rejector:(RCTPromiseRejectBlock)reject)
{
NSError *error = nil;
@try {
NSString *asString = [self getPlistAsString:localPath];
resolve(asString);
}
@catch (NSException *exception) {
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"];
error = [[NSError alloc] initWithDomain:@"react-native-read-plist" code:1 userInfo:info];
reject(@"read_plist_promise", @"read Plist error", error);
}
}
- (NSString *)getPlistAsString: (NSString *)localPath {
NSData *data = [NSData dataWithContentsOfFile:localPath];
NSError *error = nil;
id plistFile = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:&error];
NSData *asXML = [NSPropertyListSerialization dataWithPropertyList:plistFile format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
NSString *asString = [[NSString alloc] initWithData:asXML encoding:NSUTF8StringEncoding];
return asString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment