Skip to content

Instantly share code, notes, and snippets.

@stecman
Created August 22, 2016 22:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stecman/71a5cead43eeef8fbc4c54eb97fe5ebd to your computer and use it in GitHub Desktop.
Save stecman/71a5cead43eeef8fbc4c54eb97fe5ebd to your computer and use it in GitHub Desktop.
React Native get relative time
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
@interface TimerModule : NSObject <RCTBridgeModule>
@end
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class TimerModule extends ReactContextBaseJavaModule {
public TimerModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "Timer";
}
/**
* Return a relative unit of time in seconds that cannot be influenced by the user
* @param promise
*/
@ReactMethod
public void getRelativeTime(Promise promise) {
// System time in milliseconds
long time = android.os.SystemClock.elapsedRealtime();
// React Native bridge complains if we try to pass back a long directly
promise.resolve(Long.toString(time / 1000));
}
}
#import "TimerModule.h"
#include <sys/sysctl.h>
@implementation TimerModule
RCT_EXPORT_MODULE(Timer);
/**
* Return a relative time in seconds that can't be tampered with by the user
*/
RCT_EXPORT_METHOD(getRelativeTime: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
resolve([NSString stringWithFormat:@"%ld", [self uptime]]);
}
/**
* Get the system up time in seconds
*
* Method originally from here:
* http://stackoverflow.com/questions/12488481/getting-ios-system-uptime-that-doesnt-pause-when-asleep
*/
- (time_t)uptime
{
struct timeval boottime;
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
size_t size = sizeof(boottime);
time_t now;
time_t uptime = -1;
(void) time(&now);
if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) {
uptime = now - (boottime.tv_sec);
}
return uptime;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment