react-native#Platform JavaScript Examples

The following examples show how to use react-native#Platform. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: analytics.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
async function reportBluetoothState() {
  if (Platform.OS === 'android') {
    return;
  }
  // lay thoi gian ban len truoc do
  let previousTime = (await getTimeAnalyticsBle()) || 0;
  previousTime = new Date(previousTime);
  const previousHour = previousTime.setMinutes(0, 0, 0);

  // lay thoi gian hien tai
  const currentTime = new Date();
  const currentHour = currentTime.setMinutes(0, 0, 0);

  // 1 tieng gui thong ke len server 1 lan
  if (previousHour !== currentHour) {
    const hour = currentTime.getHours();
    const isEnable = await getBluetoothState();
    const eventName = `Bluetooth_${isEnable ? 'ON' : 'OFF'}_${hour}_hour`;
    firebase.analytics().logEvent(eventName, {value: 'bluetoothStatus'});
    setTimeAnalyticsBle(currentTime);
  }
}
Example #2
Source File: BTCWallet.js    From RRWallet with MIT License 6 votes vote down vote up
async exportMnemonic(pwd) {
    if (!pwd || pwd.length == 0) {
      throw new Error("密码不能为空");
    }
    let result = await RRRNBitcoin.exportMnemonic(this.id, pwd);
    if (Platform.OS === "android") {
      result = result.mnemonic;
    }
    return result;
  }
Example #3
Source File: ClusteredMapView.js    From guardioes-app with Apache License 2.0 6 votes vote down vote up
constructor(props) {
    super(props)

    this.state = {
      data: [], // helds renderable clusters and markers
      region: props.region || props.initialRegion, // helds current map region
      unhealthy: [] 
    }

    this.isAndroid = Platform.OS === 'android'
    this.dimensions = [props.width, props.height]

    this.mapRef = this.mapRef.bind(this)
    this.onRegionChangeComplete = this.onRegionChangeComplete.bind(this)
  }
Example #4
Source File: requestPermissions.js    From covid-alert with Apache License 2.0 6 votes vote down vote up
export async function verifyLocationPermissions() {
  console.log('Requesting location permission')
  const res = await promiseTimeout(
    FIVE_S_IN_MS,
    request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_ALWAYS
      })
    )
  )
  if (res !== RESULTS.GRANTED) {
    console.error('Location permission not granted!', { res })
    return false
  }
  return true
}
Example #5
Source File: styles.js    From haven with MIT License 6 votes vote down vote up
onboardingStyles = {
  header: {
    height: (SCREEN_WIDTH * bgRatio) + (Platform.OS === 'ios' ? statusbarHeight : 0),
  },
  headerContent: {
    flex: 1,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    width: '30%',
  },
}
Example #6
Source File: index.js    From react-native-in-app-review with MIT License 6 votes vote down vote up
//ios version check

function isModuleAvailable() {
  if (Platform.OS === 'android') {
    if (!InAppReviewModule) {
      throw new Error(
        'InAppReview native module not available, did you forget to link the library?',
      );
    }
    return true;
  } else if (Platform.OS === 'ios') {
    if (!RNInAppReviewIOS) {
      throw new Error(
        'InAppReview native module not available, did you forget to link the library?',
      );
    }
    return true;
  } else {
    return false;
  }
}
Example #7
Source File: useKeyboardStatus.js    From react-native-country-codes-picker with MIT License 6 votes vote down vote up
useKeyboardStatus = () => {
    const [isOpen, setIsOpen] = useState(false);
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    const keyboardHideListener = useRef(null);
    const keyboardShowListener = useRef(null);

    const onKeyboardShow = e => {
        setKeyboardHeight(e.endCoordinates.height);
        setIsOpen(true);
    }

    const onKeyboardHide = () => {
        setKeyboardHeight(0);
        setIsOpen(false);
    }

    useEffect(() => {
        keyboardShowListener.current = Keyboard.addListener('keyboardDidShow', onKeyboardShow);
        keyboardHideListener.current = Keyboard.addListener('keyboardDidHide', onKeyboardHide);

        return () => {
            keyboardShowListener.current.remove();
            keyboardHideListener.current.remove();
        };
    },[]);

    return {
        isOpen: isOpen,
        keyboardHeight: keyboardHeight,
        keyboardPlatform: Platform.OS
    };
}
Example #8
Source File: react-native.js    From fuel-js with Apache License 2.0 6 votes vote down vote up
export function generateSecureRandom(length) {
    if (Platform.OS !== 'ios' && Platform.OS !== 'android') {
        throw Error('react-native-securerandom is currently only available for iOS and Android');
    }

    if (!RNSecureRandom || !RNSecureRandom.generateSecureRandomAsBase64) {
        throw Error('react-native-securerandom is not properly linked');
    }

    return RNSecureRandom.generateSecureRandomAsBase64(length).then(base64 => toByteArray(base64));
}
Example #9
Source File: cameraUpload.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
getUploadName = (asset) => {
    //new Date(asset.timestamp * 1000).toLocaleString().split(" ").join("_").split(",").join("_").split(":").join("_").split(".").join("_") + "_" + 

    if(Platform.OS == "ios"){
        return asset.rawId.split("/").join("_").split("-").join("_") + "." + (asset.type.indexOf("image") !== -1 ? "jpg" : "mp4")
    }
    else{
        return getFilenameFromPath(asset.uri)
    }
}
Example #10
Source File: helpers.js    From React-Messenger-App with MIT License 6 votes vote down vote up
/**
 * Create touchable component based on passed parameter and platform.
 * It also returns default props for specific touchable types.
 */
export function makeTouchable(TouchableComponent) {
  const Touchable = TouchableComponent || Platform.select({
    android: TouchableNativeFeedback,
    ios: TouchableHighlight,
    default: TouchableHighlight,
  });
  let defaultTouchableProps = {};
  if (Touchable === TouchableHighlight) {
    defaultTouchableProps = { underlayColor: 'rgba(0, 0, 0, 0.1)' };
  }
  return { Touchable, defaultTouchableProps };
}
Example #11
Source File: index.css.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
styles = StyleSheet.create({
  container: {
    height: heightPercentageToDP((50 / 720) * 100),
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
  },
  btnBack: {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: 0,
    height: heightPercentageToDP((50 / 720) * 100),
    justifyContent: 'center',
    zIndex: 99,
  },
  textTitle: {
    fontSize: fontSize.huge,
    textAlign: 'center',
    color: '#000',
  },
  icon: {
    paddingLeft: 20,
    paddingRight: 30,
    ...Platform.select({
      ios: {
        paddingTop: 5,
      },
    }),
  },
  title: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
})
Example #12
Source File: CalendarComponent.js    From react-native-todolist with MIT License 6 votes vote down vote up
async componentDidMount() {
    console.log("componentDidMount....");

    if(Platform.OS === 'android') {
      this.checkPermission();
      this.messageListener();
      //this.props.fetchAnnouncement();
    }
    this.props.fetchPlanners(true)
  }
Example #13
Source File: index.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
componentDidMount() {
    logBlueZone = [];
    this.scanBLEListener = Service.addListenerScanBLE(this.onScan);
    if (Platform.OS === 'android') {
      this.scanBluetoothListener = Service.addListenerScanBluetooth(
        this.onScan,
      );
    }
  }
Example #14
Source File: ReduxNavigation.js    From Alfredo-Mobile with MIT License 6 votes vote down vote up
componentDidMount () {
    if (Platform.OS === 'ios') return
    BackHandler.addEventListener('hardwareBackPress', () => {
      const { dispatch, nav } = this.props
      // change to whatever is your first screen, otherwise unpredictable results may occur
      if (nav.routes.length === 1 && (nav.routes[0].routeName === 'LaunchScreen')) {
        return false
      }
      // if (shouldCloseApp(nav)) return false
      dispatch({ type: 'Navigation/BACK' })
      return true
    })
  }
Example #15
Source File: App.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
function StackNav() {
  const loggedIn = useSelector(i => i.loggedIn);
  return <Stack.Navigator
    screenOptions={({ navigation, route }) => ({
      gestureEnabled: Platform.OS == 'ios',
      // animationEnabled: false,
      header: (props) => <Header {...(props || {})} />,

    })}>
    {loggedIn && <>
      <Stack.Screen
        name="_redirect"
        component={RedirectScreen}
      />
      {screens.filter(i => !i.nologin).map(screen => <Stack.Screen
        key={screen.name}
        name={screen.name}
        component={screen.screen}
      />)}
    </>}
    <Stack.Screen
      name="Auth"
      options={{
        title: "Authenticate",
      }}
      component={AuthScreen}
    />
    {screens.filter(i => i.nologin).map(screen => <Stack.Screen
      key={screen.name}
      name={screen.name}
      component={screen.screen}
    />)}
  </Stack.Navigator>
}
Example #16
Source File: notifyScheduler.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
bluetoothChangeListener = isEnable => {
  if (Platform.OS === 'android') {
    return;
  }

  const {iOSScheduleScanNotification, iOSScanNotification} = configuration;
  if (isEnable) {
    // Clear notification
    clearScheduleScanNotification(iOSScheduleScanNotification);
    clearScanNotification(iOSScanNotification);
  } else {
    // Create notification
    clearScheduleScanNotification(iOSScheduleScanNotification);
    clearScanNotification(iOSScanNotification);
    createScheduleScanNotification(iOSScheduleScanNotification);
    createScanNotification(iOSScanNotification);
  }
}
Example #17
Source File: Notifications.ios.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
async function registerForPushNotificationsAsync() {
  let token;
  if (Constants.isDevice) {
    const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  console.log('got',token)

  return token;
}
Example #18
Source File: notifyScheduler.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
scanNotification_ChangeLanguage = async () => {
  if (Platform.OS === 'android') {
    return;
  }
  const isEnable = await getBluetoothState();
  if (!isEnable) {
    createScanNotification();
  }
}
Example #19
Source File: font.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
export default function font(weight) {
  var f = 'Roboto'
  if(Platform.OS=="web") return {
    fontWeight: (weight||400).toString()
  }
  return {
    fontFamily: {
      100: `${f}_100Thin`,
      200: `${f}_200ExtraLight`,
      300: `${f}_300Light`,
      400: `${f}_400Regular`,
      500: `${f}_500Medium`,
      600: `${f}_600SemiBold`,
      700: `${f}_700Bold`,
      bold: `${f}_700Bold`,
      800: `${f}_800ExtraBold`,
      900: `${f}_900Black`
    }[weight] || `${f}_400Regular`
  };
}
Example #20
Source File: bluezone.js    From bluezone-app with GNU General Public License v3.0 6 votes vote down vote up
registerTokenFirebase = (
  TokenFirebase,
  success = _defaultFunc,
  failure = _defaultFunc,
) => {
  const options = {
    method: 'post',
    data: {
      TokenFirebase: TokenFirebase,
      TypeOS: Platform.OS,
    },
    url: `${DOMAIN}/api/App/RegisterUser`,
    timeout: 10000,
  };

  const _success = response => {
    log.info(msg.REGISTER_TOKEN_FIREBASE_SUCCESS, response);
    success(response.data);
  };

  const _failure = e => {
    log.error(msg.REGISTER_TOKEN_FIREBASE_FAILURE, e);
    failure(e);
  };

  axios(options).then(response => {
    if (response.status === 200 && response.data.isOk === true) {
      _success(response);
    } else {
      _failure(response);
    }
  }, createErrorFn(_failure));
}
Example #21
Source File: ProductPolicy.js    From haven with MIT License 5 votes vote down vote up
render() {
    const { policy, content } = this.props;
    const { showModal, showSpinner } = this.state;
    return (
      <ProductSection>
        <OptionGroup onPress={this.handleShowModal} noBorder>
          <Text style={styles.title}>{policy}</Text>
        </OptionGroup>
        <OBLightModal
          animationType="slide"
          transparent
          visible={showModal}
          onRequestClose={this.handleHideModal}
        >
          <Header modal left={<NavCloseButton />} onLeft={this.handleHideModal} />
          {_.isEmpty(content) ? (
            this.renderEmptyContent(policy)
          ) : (
            <View style={styles.webviewWrapper}>
              <WebView
                onLoadStart={this.handleHideSpinner}
                onError={this.handleHideSpinner}
                originWhitelist={['*']}
                source={{
                  html: `${cssCode} ${content}`,
                  baseUrl: '',
                }}
                // injectedJavaScript={jsCode}
                // javaScriptEnabled
                scalesPageToFit={Platform.OS === 'android'}
                useWebKit={false}
              />
            </View>
          )}
          {!_.isEmpty(content) && showSpinner && (
            <View style={styles.activityIndicator}>
              <ActivityIndicator size="large" color="#8a8a8f" />
            </View>
          )}
        </OBLightModal>
      </ProductSection>
    );
  }
Example #22
Source File: AppInfo.js    From RRWallet with MIT License 5 votes vote down vote up
async install(path, progress) {
    if (Platform.OS == "ios") {
      Linking.openURL(path);
    } else {
      const publicPath = `/data/data/${this.bundleId}/files/public`;
      if (!(await RNFS.exists(publicPath))) {
        await RNFS.mkdir(publicPath);
      }
      const filePath = `${publicPath}/rrwallet.apk`;
      if (await RNFS.exists(filePath)) {
        await RNFS.unlink(filePath);
      }
      let percent = 0;
      const ret = RNFS.downloadFile({
        fromUrl: path,
        toFile: filePath,
        connectionTimeout: 1000 * 120,
        progressDivider: 1,
        progress: ({ contentLength, bytesWritten }) => {
          percent = parseFloat((bytesWritten / contentLength).toFixed(2));
          if (!isFinite(percent) || isNaN(percent)) {
            return;
          }
          progress && progress(percent);
        },
      });
      const res = await ret.promise;
      if (percent !== 1) {
        throw new Error(i18n.common("update-download-failed"));
      }
      await sleep(400);
      try {
        await RRRNDevice.installAPK(filePath);
      } catch (error) {
        const logger = require("../../util/logger").default;
        logger.error(new Error("安装失败"));
        alert(error);
      }
    }
  }
Example #23
Source File: NewsFeedFooter.js    From haven with MIT License 5 votes vote down vote up
BUTTON_WRAPPER_PADDING = Platform.OS === 'ios' ? 15 : 10
Example #24
Source File: index.css.js    From bluezone-app with GNU General Public License v3.0 5 votes vote down vote up
styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    ...Platform.select({
      ios: {
        paddingTop: 0,
      },
      android: {
        paddingTop: 20,
      },
    }),
  },
  textHeader: {
    color: '#015cd0',
    fontSize: fontSize.bigger,
  },
  buttonSendSquare: {
    width: '100%',
    backgroundColor: '#119a01',
    marginVertical: 25,
    borderRadius: 3,
  },
  header: {
    height: 80,
    alignItems: 'center',
    justifyContent: 'flex-end',
    width: '100%',
  },
  input: {
    height: 40,
    borderColor: '#dddddd',
    borderWidth: 1,
    marginTop: 13,
    width: '100%',
    borderRadius: 3,
    paddingHorizontal: 12,
    fontFamily: 'OpenSans-Regular',
    fontSize: fontSize.small,
    color: '#000000',
  },
  inputFirst: {
    height: 40,
    borderColor: '#dddddd',
    borderWidth: 1,
    marginTop: 5,
    width: '100%',
    borderRadius: 3,
    paddingHorizontal: 12,
    fontFamily: 'OpenSans-Regular',
    fontSize: fontSize.small,
    color: '#000000',
  },
  containerForm: {
    width: '100%',
  },
  title: {
    fontSize: fontSize.normal,
    lineHeight: 25,
  },
  checkbox: {
    fontSize: fontSize.smaller,
  },
  textButton: {
    fontSize: fontSize.normal,
  },
})
Example #25
Source File: PayPanel.js    From haven with MIT License 5 votes vote down vote up
styles = {
  wrapper: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
  },
  question: {
    marginVertical: 20,
    color: formLabelColor,
    fontSize: 16,
  },
  content: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  item: {
    flex: 1,
  },
  itemContent: {
    alignItems: 'center',
    paddingVertical: 15,
  },
  leftBorder: {
    borderLeftWidth: 1,
    borderColor,
  },
  imageContainer: {
    width: 56,
    height: 56,
    backgroundColor: '#e8f7e7',
    borderRadius: 28,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center',
    ...Platform.select({
      ios: { paddingTop: 5 },
      android: { paddingTop: 0 },
    }),
  },
  logo: {
    width: 44,
    height: 22,
  },
  externalImageGap: {
    // paddingTop: 5,
  },
  title: {
    marginTop: 12,
    fontSize: 14,
    color: '#404040',
  },
  insufficient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  insufficientText: {
    color: warningColor,
    fontSize: 12,
  },
}
Example #26
Source File: bluezone.js    From bluezone-app with GNU General Public License v3.0 5 votes vote down vote up
_createAndSendOTPCode = (
  PhoneNumber,
  TokenFirebase,
  success = _defaultFunc,
  failure = _defaultFunc,
  numberRetry = 0,
) => {
  const options = {
    method: 'POST',
    data: {
      PhoneNumber: PhoneNumber,
      TokenFirebase: TokenFirebase,
      TypeOS: Platform.OS,
    },
    url: `${DOMAIN}/api/App/CreateAndSendOTPCode`,
    timeout: 10000,
  };

  const _success = response => success(response.data);

  axios(options).then(response => {
    if (response.status === 200 && response.data.isOk === true) {
      _success(response);
      return;
    }

    // Co gang dang ki lai token firebase neu co loi
    if (
      (response.data.Status ===
        CreateAndSendOTPCodeErrorCode.TOKEN_FIREBASE_KHONG_HOP_LE ||
        response.data.Status ===
          CreateAndSendOTPCodeErrorCode.TOKEN_FIREBASE_CHUA_DANG_KI) &&
      numberRetry < 1
    ) {
      numberRetry++;
      syncTokenFirebase(
        _tokenFirebase => {
          _createAndSendOTPCode(
            PhoneNumber,
            _tokenFirebase,
            success, // Cho nay bat buoc la success goc tren param, khong duoc dung _success
            failure,
            numberRetry,
          );
        },
        () => failure(response), // Sync token firebay loi thi dung luon, day response goc ra
      );
    } else {
      failure(response);
    }
  }, createErrorFn(failure));
}
Example #27
Source File: PanelViewBase.js    From haven with MIT License 5 votes vote down vote up
WRAPPER_HEIGHT = Platform.OS === 'ios' && WINDOW_HEIGHT < 800 ? 224 : 234
Example #28
Source File: InAppNotification.js    From RRWallet with MIT License 5 votes vote down vote up
styles = StyleSheet.create({
  main: {
    backgroundColor: "#FFFFFF",
    paddingTop: Platform.select({
      ios: 24 + (device.isIPhoneX ? 24 : 0),
      android: 14,
    }),
    paddingBottom: 16,
    paddingHorizontal: 20,
    width: device.windowSize.width,
    flexDirection: "row",
  },
  container: {
    flex: 1,
    marginLeft: 7,
    marginTop: 3,
  },
  title: {
    fontSize: 16,
    color: theme.textColor.primary,
    fontWeight: theme.fontWeight.medium,
  },
  content: {
    marginTop: 6,
    fontSize: 14,
    lineHeight: 20,
    color: theme.textColor.primary,
  },
  date: {
    fontSize: 14,
    color: theme.textColor.mainTitle,
    fontFamily: theme.alphanumericFontFamily,
  },
  row: {
    marginTop: 6,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  detail: {
    color: theme.linkColor,
    fontSize: 12,
  },
  iconWrap: {
    height: 24,
    width: 24,
  },
  shadow: {
    width: "100%",
  },
})
Example #29
Source File: FeedItemFooter.js    From haven with MIT License 5 votes vote down vote up
render() {
    const { style } = this.props;
    const { like = 0, repost = 0, comment = 0 } = this.getReactionStatus();
    const isCommented = this.isCommented();
    const isReposted = this.isReposted();
    const isLiked = this.isLiked();
    return (
      <View style={[styles.wrapper, style]}>
        <TouchableWithoutFeedback onPress={this.comment}>
          <View style={styles.btn}>
            <Feather
              style={styles.buttonIcon}
              name={Platform.OS === 'ios' ? 'message-circle' : 'message-square'}
              size={19}
              color={isCommented ? brandColor : secondaryTextColor}
            />
            {comment > 0 && <Text style={[styles.btnText, isCommented && styles.activeText]}>{comment}</Text>}
          </View>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={this.repost}>
          <View style={styles.btn}>
            <Feather
              style={styles.buttonIcon}
              name="repeat"
              size={19}
              color={isReposted ? brandColor : secondaryTextColor}
            />
            {repost > 0 && <Text style={[styles.btnText, isReposted && styles.activeText]}>{repost}</Text>}
          </View>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={this.like}>
          <View style={styles.btn}>
            <Feather
              style={styles.buttonIcon}
              name="thumbs-up"
              size={19}
              color={isLiked ? brandColor : secondaryTextColor}
            />
            {like > 0 && <Text style={[styles.btnText, isLiked && styles.activeText]}>{like}</Text>}
          </View>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={this.share}>
          <View style={styles.btn}>
            <Feather
              style={styles.buttonIcon}
              name={Platform.OS === 'ios' ? 'share' : 'share-2'}
              size={19}
              color={secondaryTextColor}
            />
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  }