<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Salman Khan on Medium]]></title>
        <description><![CDATA[Stories by Salman Khan on Medium]]></description>
        <link>https://medium.com/@salmankn033?source=rss-3304baff9666------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XAUIJL9ApekMhkLh86pI5A.png</url>
            <title>Stories by Salman Khan on Medium</title>
            <link>https://medium.com/@salmankn033?source=rss-3304baff9666------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:38:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salmankn033/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Secure a React Native App in Production (Real-World Approach)]]></title>
            <link>https://medium.com/@salmankn033/how-to-secure-a-react-native-app-in-production-real-world-approach-67cc429c2ffd?source=rss-3304baff9666------2</link>
            <guid isPermaLink="false">https://medium.com/p/67cc429c2ffd</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-security]]></category>
            <category><![CDATA[react-nativer-a]]></category>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[react-native-security]]></category>
            <dc:creator><![CDATA[Salman Khan]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 19:29:39 GMT</pubDate>
            <atom:updated>2026-02-19T19:33:42.552Z</atom:updated>
            <content:encoded><![CDATA[<p>When building a React Native app, many developers focus heavily on UI, performance, and features — but security often becomes an afterthought. In reality, security should be part of your architecture from day one.</p><p>In this article, I’ll explain how to secure a React Native app at a professional, production level — based on real-world experience, not just theory.</p><h3>1️⃣ Secure Your Network Layer</h3><p>Every mobile app communicates with a backend. If your API communication is not secure, everything else becomes meaningless.</p><p><strong>Best practices:</strong></p><ul><li>Always use HTTPS (no exceptions).</li><li>Enforce TLS 1.2 or higher.</li><li>Disable all HTTP traffic in production.</li><li>Never expose secret API keys inside the app.</li></ul><p>For apps handling sensitive data (finance, admin dashboards, private user data), implement <strong>SSL pinning</strong>. This ensures your app only trusts your server’s certificate and prevents man-in-the-middle attacks.</p><h3>2️⃣ Handle Authentication the Right Way</h3><p>A common mistake is storing JWT tokens in AsyncStorage. That’s not secure.</p><p>Instead:</p><ul><li>Store tokens using:</li><li>react-native-keychain</li><li>expo-secure-store</li><li>Keep access tokens short-lived.</li><li>Use refresh tokens carefully.</li><li>Rotate tokens when possible.</li></ul><p>For high-security apps, you can add biometric authentication (Face ID / Fingerprint) before accessing sensitive screens.</p><h3>3️⃣ Protect Sensitive Data on the Device</h3><p>Anything stored locally can potentially be accessed on a compromised device.</p><p>To improve security:</p><ul><li>Use encrypted storage.</li><li>Avoid saving unnecessary sensitive data.</li><li>Remove console logs in production.</li><li>Disable debugging tools in release builds.</li></ul><p>Never assume the device is fully secure.</p><h3>4️⃣ Prevent Reverse Engineering</h3><p>React Native apps ship with a JavaScript bundle, which means the code can be extracted.</p><p>To reduce risk:</p><ul><li>Enable Hermes engine.</li><li>Enable Proguard / R8 for Android.</li><li>Minify and obfuscate release builds.</li><li>Disable developer menus and debugging in production.</li></ul><p>While no app is 100% impossible to reverse engineer, these steps significantly increase the effort required.</p><h3>5️⃣ Detect Compromised Devices</h3><p>For apps that require strong security (banking, fintech, enterprise tools):</p><ul><li>Detect rooted Android devices.</li><li>Detect jailbroken iOS devices.</li><li>Detect emulators or debugging attempts.</li></ul><p>You can choose to block access or limit functionality when a compromised device is detected.</p><h3>6️⃣ Secure the Backend (Most Important Layer)</h3><p>Many developers focus only on frontend security. That’s a mistake.</p><p>Your backend must:</p><ul><li>Validate all inputs.</li><li>Verify authentication on every request.</li><li>Implement role-based access control.</li><li>Apply rate limiting.</li><li>Protect against brute-force attacks.</li></ul><p>Never trust the frontend — always validate on the server.</p><h3>7️⃣ Secure Payments and Third-Party Services</h3><p>If your app processes payments:</p><ul><li>Use official SDKs (Stripe, Apple In-App Purchase, Google Play Billing).</li><li>Never process payment logic manually.</li><li>Never expose private keys in the app.</li></ul><p>For push notifications, avoid sending sensitive information directly in notification payloads.</p><h3>8️⃣ Separate Environments Properly</h3><p>Maintain separate environments for:</p><ul><li>Development</li><li>Staging</li><li>Production</li></ul><p>Use different API URLs, credentials, and signing keys. Never mix production secrets with development builds.</p><h3>Final Thoughts</h3><p>Mobile app security is not about adding one package. It’s about building layers of protection:</p><ul><li>Secure network communication</li><li>Safe token storage</li><li>Code obfuscation</li><li>Backend validation</li><li>Device integrity checks</li></ul><p>Even if someone decompiles your app or inspects network traffic, they should not be able to access sensitive data or manipulate your system.</p><p>That’s what real production-level security looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isMgt7lfaX576WrN2BqzbA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67cc429c2ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Validate Forms in React Native With React Hook Form and Yup to Avoid Too Many States and…]]></title>
            <link>https://medium.com/@salmankn033/how-to-validate-forms-in-react-native-with-react-hook-form-and-yup-to-avoid-too-many-states-5cd74faefead?source=rss-3304baff9666------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd74faefead</guid>
            <category><![CDATA[avoid-state-using]]></category>
            <category><![CDATA[app-optimization]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[form-validation]]></category>
            <category><![CDATA[yup]]></category>
            <dc:creator><![CDATA[Salman Khan]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 16:05:37 GMT</pubDate>
            <atom:updated>2025-03-14T17:53:06.503Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Validate Forms in React Native With React Hook Form and Yup to Avoid Too Many States and Rendering</h3><p>If you’re tired of managing too many states and complex form validations for form handling, this article is for you.</p><p>I explain how to reduce excessive state usage and prevent unnecessary re-renders, helping you optimize and improve your app’s performance.</p><p>By following these best practices, you can improve performance and optimize your app efficiently.</p><p>Form validation is a crucial part of any mobile app. It ensures users enter the correct information, prevents errors, and improves the user experience. In this guide, I’ll walk you through how to implement form validation in React Native using react-hook-form and yup.</p><p>By the end of this tutorial, you’ll have a fully functional form with validation rules for firstName lastName, email, and password fields. Let’s dive in!</p><h3>Why use React Hook Form and Yup?</h3><ul><li>👉 <strong>Improves Performance — </strong>React Hook Form minimizes re-renders by using uncontrolled components, unlike useState, which can cause excessive re-renders when handling form state.<br>It reduces the need for multiple useState hooks, improving performance.</li><li>👉 <strong>Less Boilerplate Code</strong> — It makes form handling much easier with built-in methods like register and handleSubmit, so you don’t have to write a lot of repetitive code.</li><li>👉 <strong>Simple &amp; Powerful Validation</strong> — Yup allows you to define validation rules in a clean and readable way, making your code more structured.</li><li>👉 <strong>Better User Experience</strong> — Users get real-time validation feedback, helping them fix mistakes immediately.</li><li>👉 <strong>Perfect for React Native</strong> — Works smoothly with TextInput, Picker, and even third-party UI libraries.</li></ul><h3>Step 1: Install the Required Packages</h3><p>First, you need to install the necessary dependencies. Run the following commands in your project:</p><pre>npm install react-hook-form yup @hookform/resolvers <br>or<br>yarn add react-hook-form yup @hookform/resolvers</pre><h3>What are these packages for?</h3><ul><li><strong>react-hook-form</strong>: Manages form state efficiently without unnecessary re-renders.</li><li><strong>yup</strong>: Provides an easy way to define validation rules for form fields.</li><li><strong>@hookform/resolvers</strong>: Connects yup with react-hook-form so we can validate our form easily.</li></ul><h3>Step 2: Create a Custom Input Component</h3><p>Instead of using the default TextInput everywhere, let’s create a reusable TextInput component that works with react-hook-form.</p><ul><li><strong>userController: </strong>it shares the same props and methods as Controller. It’s useful for creating reusable Controlled input.<br>useController is a <strong>React Hook Form</strong> hook that provides direct access to a form field&#39;s <strong>value</strong>, <strong>onChange</strong>, <strong>onBlur</strong>, and <strong>validation state</strong>. It allows you to manually control form fields while still benefiting from React Hook Form’s optimized performance and validation system.</li><li>It’s an alternative to the &lt;Controller&gt; component but gives more flexibility, especially when working with <strong>custom input components</strong> in React Native.</li></ul><pre>import { Control, useController } from &#39;react-hook-form&#39;;<br>const { field } = useController({<br>    control,<br>    name,<br>  });</pre><h3>TextInput.tsx</h3><pre>import React from &#39;react&#39;;<br>import { Control, useController } from &#39;react-hook-form&#39;;<br>import { TextInput as RNTextInput, StyleProp, TextStyle } from &#39;react-native&#39;;<br>// Define the props for our custom input<br>interface CustomTextInputProps {<br>  style?: StyleProp&lt;TextStyle&gt;;<br>  name: string;<br>  control: Control&lt;any&gt;;<br>  placeholder: string;<br>  secureTextEntry?: boolean;<br>  placeholderTextColor?: string;<br>}<br>const TextInput: React.FC&lt;CustomTextInputProps&gt; = ({<br>  style,<br>  name,<br>  control,<br>  placeholder,<br>  secureTextEntry,<br>  placeholderTextColor,<br>}) =&gt; {<br>  // Connect the input to the form using useController<br>  const { field } = useController({<br>    control,<br>    name,<br>  });<br><br> return (<br>    &lt;RNTextInput<br>      value={field.value} // The current value of the input<br>      onChangeText={field.onChange} // Updates the form state when text changes<br>      placeholder={placeholder} // Placeholder text<br>      placeholderTextColor={placeholderTextColor || &#39;#888&#39;}<br>      secureTextEntry={secureTextEntry} // Enables password hiding if needed<br>      style={style} // Custom styles<br>    /&gt;<br>  );<br>};<br><br>export default TextInput;</pre><h3>Explanation:</h3><ul><li><strong>We use </strong><strong>useController</strong>: This connects the input field to react-hook-form.</li><li><strong>Props for customization</strong>: The component accepts placeholder, secureTextEntry, and style for flexibility.</li><li><strong>Controlled input</strong>: The value is controlled by react-hook-form, ensuring consistent state management.</li></ul><h3>Step 3: Build the Form with Validation</h3><p>Now that we have our custom TextInput, let’s create the main form and apply validation rules using yup.</p><ul><li><strong><em>YupResolver</em></strong> connects yup with react-hook-form.</li><li>In <strong><em>formSchema,</em></strong> we describe the form validation using yup.</li><li>Set a separate name for every Textinput</li><li>If we need to retrieve a single value, we usegetValues(&quot;fieldName&quot;), e.g., getValues(&quot;firstName&quot;).</li><li><strong><em>errors</em></strong> return the form errors.</li><li>handleSubmit(handleNextAction) ensures only valid data is logged.</li><li>On <strong><em>handleNextAction,</em></strong> we get all the data in the data props.</li></ul><h3>Forms.tsx</h3><pre>import {StyleSheet, Text, TouchableOpacity, View} from &#39;react-native&#39;;<br>import React from &#39;react&#39;;<br>import TextInput from &#39;../components/TextInput&#39;;<br>import * as Yup from &#39;yup&#39;;<br>import {yupResolver} from &#39;@hookform/resolvers/yup&#39;;<br>import {useForm} from &#39;react-hook-form&#39;;<br>interface FormData {<br>  firstName: string;<br>  lastName: string;<br>  email: string;<br>  password: string;<br>}<br>// Define validation rules using Yup<br>const formSchema = Yup.object().shape({<br>  firstName: Yup.string().required(&#39;First name is required&#39;),<br>  lastName: Yup.string().required(&#39;Last name is required&#39;),<br>  email: Yup.string()<br>    .required(&#39;Email address is required&#39;)<br>    .email(&#39;Email must be a valid email&#39;),<br>  password: Yup.string()<br>    .min(8, &#39;Password must be at least 8 characters long.&#39;)<br>    .matches(/[A-Z]/, &#39;Password must contain at least one uppercase letter.&#39;)<br>    .matches(/[a-z]/, &#39;Password must contain at least one lowercase letter.&#39;)<br>    .matches(/[0-9]/, &#39;Password must contain at least one number.&#39;)<br>    .matches(<br>      /[@$!%*?&amp;#]/,<br>      &#39;Password must contain at least one special character.&#39;,<br>    )<br>    .matches(<br>      /[@$!%*?&amp;#]/,<br>      &#39;Password must contain at least one special character.&#39;,<br>    )<br>    .test(<br>      &#39;no-leading-space&#39;,<br>      &#39;Password cannot start with a space.&#39;,<br>      value =&gt; !value || value.charAt(0) !== &#39; &#39;,<br>    )<br>    .test(<br>      &#39;no-trailing-space&#39;,<br>      &#39;Password cannot end with a space.&#39;,<br>      value =&gt; !value || value.charAt(value.length - 1) !== &#39; &#39;,<br>    )<br>    .required(&#39;Password is required&#39;),<br>});<br><br>const Forms = () =&gt; {<br>  // Initialize the form with default values and the validation schema<br>  const {<br>    control,<br>    handleSubmit,<br>    formState: {errors},<br>    getValues,<br>  } = useForm&lt;FormData&gt;({<br>    defaultValues: {<br>      firstName: &#39;&#39;,<br>      lastName: &#39;&#39;,<br>      email: &#39;&#39;,<br>      password: &#39;&#39;,<br>    },<br>    resolver: yupResolver(formSchema), // Connects Yup validation to react-hook-form<br>  });<br><br>  function handleNextAction(data: FormData): unknown {<br>    console.log(&#39;form Data&#39;, data); // Handle form submission<br><br>  }<br>  console.log(&#39;testings &#39;, getValues(&#39;firstName&#39;));<br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;Text style={styles.HeaderText}&gt;Form Validations&lt;/Text&gt;<br>      &lt;TextInput<br>        control={control}<br>        name=&quot;firstName&quot;<br>        style={[<br>          styles.InputField,<br>          errors.email &amp;&amp; {borderColor: &#39;#FF0000&#39;, borderWidth: 0.5},<br>        ]}<br>        placeholder=&quot;firstName&quot;<br>        placeholderTextColor={&#39;#BFBFBF&#39;}<br>      /&gt;<br>      {errors.firstName &amp;&amp; (<br>        &lt;Text style={styles.ErrorText}&gt;{errors.firstName.message}&lt;/Text&gt;<br>      )}<br>      &lt;TextInput<br>        control={control}<br>        name=&quot;lastName&quot;<br>        style={[<br>          styles.InputField,<br>          errors.email &amp;&amp; {borderColor: &#39;#FF0000&#39;, borderWidth: 0.5},<br>        ]}<br>        placeholder=&quot;lastName&quot;<br>        placeholderTextColor={&#39;#BFBFBF&#39;}<br>      /&gt;<br>      {errors.lastName &amp;&amp; (<br>        &lt;Text style={styles.ErrorText}&gt;{errors.lastName.message}&lt;/Text&gt;<br>      )}<br>      &lt;TextInput<br>        control={control}<br>        name=&quot;email&quot;<br>        style={[<br>          styles.InputField,<br>          errors.email &amp;&amp; {borderColor: &#39;#FF0000&#39;, borderWidth: 0.5},<br>        ]}<br>        placeholder=&quot;Email&quot;<br>        placeholderTextColor={&#39;#BFBFBF&#39;}<br>      /&gt;<br>      {errors.email &amp;&amp; (<br>        &lt;Text style={styles.ErrorText}&gt;{errors.email.message}&lt;/Text&gt;<br>      )}<br>      &lt;TextInput<br>        control={control}<br>        name=&quot;password&quot;<br>        style={[<br>          styles.InputField,<br>          errors.email &amp;&amp; {borderColor: &#39;#FF0000&#39;, borderWidth: 0.5},<br>        ]}<br>        placeholder=&quot;password&quot;<br>        placeholderTextColor={&#39;#BFBFBF&#39;}<br>      /&gt;<br>      {errors.password &amp;&amp; (<br>        &lt;Text style={styles.ErrorText}&gt;{errors.password.message}&lt;/Text&gt;<br>      )}<br><br>      &lt;TouchableOpacity<br>        style={styles.SubmitButton}<br>        onPress={handleSubmit(handleNextAction)}&gt;<br>        &lt;Text&gt;Next&lt;/Text&gt;<br>      &lt;/TouchableOpacity&gt;<br><br>      &lt;Text&gt;{getValues(&#39;firstName&#39;)}&lt;/Text&gt;<br>      &lt;Text&gt;{getValues(&#39;lastName&#39;)}&lt;/Text&gt;<br>      &lt;Text&gt;{getValues(&#39;email&#39;)}&lt;/Text&gt;<br>      &lt;Text&gt;{getValues(&#39;password&#39;)}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default Forms;<br><br>const styles = StyleSheet.create({<br>  container: {<br>    marginTop: &#39;40%&#39;,<br>    paddingHorizontal: 20,<br>  },<br>  HeaderText: {<br>    fontSize: 25,<br>    textAlign: &#39;center&#39;,<br>    paddingVertical: 20,<br>  },<br>  InputField: {<br>    borderWidth: 1,<br>    borderColor: &#39;#BFBFBF&#39;,<br>    padding: 6,<br>    borderRadius: 8,<br>    paddingLeft: 10,<br>    marginTop: 20,<br>    height: 40,<br>  },<br>  ErrorText: {<br>    color: &#39;#FF0000&#39;,<br>    fontSize: 12,<br>    textAlign: &#39;left&#39;,<br><br>    marginTop: 4,<br>  },<br>  SubmitButton: {<br>    backgroundColor: &#39;#B04A36&#39;,<br>    paddingVertical: 10,<br>    borderRadius: 8,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>    marginVertical: 20,<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*anXzDDjsgT4WKvxbE0DzvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*fB6kD8JEYADDdkb600aFHA.png" /><figcaption><strong>With and without errors.</strong></figcaption></figure><p><a href="https://drive.google.com/file/d/1okq8EkO6-Hg65LomKN-I93ixRicju5FS/view?usp=sharing"><strong>Click here to watch the video</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd74faefead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Implementing In-App Subscription Purchases with React Native react-native-iap]]></title>
            <link>https://medium.com/@salmankn033/a-guide-to-implementing-in-app-subscription-purchases-with-react-native-react-native-iap-9f2cde60309c?source=rss-3304baff9666------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f2cde60309c</guid>
            <category><![CDATA[react-native-iap]]></category>
            <category><![CDATA[iap]]></category>
            <category><![CDATA[rnip]]></category>
            <dc:creator><![CDATA[Salman Khan]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 21:20:10 GMT</pubDate>
            <atom:updated>2024-03-25T22:17:22.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rf1XvZeEo7u3xvl-R3WWXA.jpeg" /></figure><p>Unlock the full earning potential of your mobile application with this comprehensive guide on integrating in-app subscription purchases (IASP) using React Native IAP. Whether you’re a seasoned developer or just starting out, this resource will provide you with step-by-step instructions and invaluable insights to effectively monetize your app’s features, content, and digital products. Learn how to seamlessly implement in-app purchases to not only generate revenue but also enhance user experience and value. Dive into the world of in-app subscriptions and elevate your app monetization strategy to new heights.<br>In this article, we will implement IAP through react-native-iap, not a third-party platform.</p><p>Follow the following steps to add iap in React Native app.<br><strong>Step 1: Install library</strong></p><pre>yarn add react-native-iap</pre><p><strong>iOS</strong></p><pre>cd ios; pod install; cd -</pre><p>Android</p><p><strong>With Android Support</strong><a href="https://react-native-iap.dooboolab.com/docs/get-started#with-android-support">​</a></p><p>Go to android/build.gradle and modify the following lines:</p><pre>buildscript {<br> ext {<br> …<br>+ supportLibVersion = &quot;28.0.0&quot;<br> }<br>}</pre><pre>buildscript {<br>  ext {<br>    ...<br>+    androidXAnnotation = &quot;1.1.0&quot;<br>+    androidXBrowser = &quot;1.0.0&quot;<br>+    minSdkVersion = 24<br>+    kotlinVersion = &quot;1.8.0&quot;<br>  }<br>  dependencies {<br>    ...<br>+   classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion&quot;<br>  }<br>}</pre><p><strong>Configure the payment provider</strong><a href="https://react-native-iap.dooboolab.com/docs/get-started#configure-the-payment-provider">​</a></p><p>You can support either Play Store, Amazon or both.</p><ul><li>To only support Play Store, go to android/app/build.gradle:</li></ul><pre>defaultConfig {<br>  ...<br>+ missingDimensionStrategy &quot;store&quot;, &quot;play&quot;<br>}</pre><p><strong>To support both:</strong></p><pre>android {<br>  ...<br>+ flavorDimensions &quot;appstore&quot;<br>+<br>+ productFlavors {<br>+   googlePlay {<br>+     dimension &quot;appstore&quot;<br>+     missingDimensionStrategy &quot;store&quot;, &quot;play&quot;<br>+   }<br>+<br>+   amazon {<br>+     dimension &quot;appstore&quot;<br>+     missingDimensionStrategy &quot;store&quot;, &quot;amazon&quot;<br>+   }<br>+ }<br>}</pre><p><strong>Set the Products in Store.</strong></p><p><strong>Step 2: Configuring Products for Apple and Android Stores</strong></p><ul><li><a href="https://www.revenuecat.com/docs/getting-started/entitlements/ios-products">IOS Product setup</a></li><li><a href="https://www.revenuecat.com/docs/getting-started/entitlements/android-products">Android Product setup</a></li></ul><p><strong>Step 3. Create handler file InAppPurchase.js</strong></p><pre>import {<br>  getProducts,<br>  initConnection,<br>  requestSubscription,<br>  getSubscriptions,<br>} from &#39;react-native-iap&#39;;<br><br>export const InAppPurchasePayments = async productId =&gt; {<br>  await makeConnection(productId);<br>  let paymentMethodCall = await handlePayment(productId);<br>  return paymentMethodCall;<br>};<br><br>const makeConnection = async myProductId =&gt; {<br>  await initConnection();<br>  await getProducts({skus: [myProductId]});<br>  await getSubscriptions({skus: [myProductId]});<br>};<br><br>const handlePayment = async myProductId =&gt; {<br>  const subscriptions = await getSubscriptions({skus: [myProductId]});<br>  let desiredOfferToken;<br><br>  if (<br>    subscriptions &amp;&amp;<br>    subscriptions.length &gt; 0 &amp;&amp;<br>    subscriptions[0]?.subscriptionOfferDetails &amp;&amp;<br>    subscriptions[0].subscriptionOfferDetails.length &gt; 0<br>  ) {<br>    desiredOfferToken =<br>      subscriptions[0].subscriptionOfferDetails[0]?.offerToken || &#39;offerToken&#39;;<br>  } else {<br>    desiredOfferToken = &#39;offerToken&#39;;<br>  }<br>  let payment = await requestSubscription({<br>    sku: myProductId,<br>    ...(desiredOfferToken &amp;&amp; {<br>      subscriptionOffers: [<br>        {<br>          sku: myProductId,<br>          offerToken: desiredOfferToken,<br>        },<br>      ],<br>    }),<br>  })<br>    .then(async requestSubscriptionIAP =&gt; {<br>      if (<br>        requestSubscriptionIAP &amp;&amp;<br>        (requestSubscriptionIAP[0]?.transactionReceipt ||<br>          requestSubscriptionIAP?.transactionReceipt)<br>      ) {<br>        return {<br>          detail: requestSubscriptionIAP,<br>          success: true,<br>        };<br>      } else {<br>        return {<br>          detail: requestSubscriptionIAP,<br>          success: false,<br>        };<br>      }<br>    })<br>    .catch(error =&gt; {<br>      return error;<br>    });<br><br>  return payment;<br>};</pre><p><strong>Step 4: Call the Configure the code.</strong></p><p>Call the functions in the required file.</p><pre>import {InAppPurchasePayments} from &#39;../Utils/Functions/InAppPurchase&#39;;<br>import {<br>  getAvailablePurchases,<br>  getSubscriptions,<br>  initConnection,<br>} from &#39;react-native-iap&#39;;<br></pre><p>call the checkPurchaseInfo function in useEffect to check the purchase status.</p><pre>const SKU_IDs = &#39;mysubscription.year.removeads&#39;;<br> React.useEffect(() =&gt; {<br>    checkPurchaseInfo();<br>   <br>  }, []);<br>  const checkPurchaseInfo = async () =&gt; {<br>    try {<br>      await initConnection();<br>      await getSubscriptions({skus: [SKU_IDs]});<br>      const availablePurchases = await getAvailablePurchases();<br>      // Check if there are any active subscriptions<br>      const hasActiveSubscription = availablePurchases.some(<br>        purchase =&gt; purchase.productId === SKU_IDs,<br>      );<br>      setShowAds(!hasActiveSubscription);<br>    } catch (error) {<br>      Alert.alert(error);<br>      console.log(&#39;Error checking subscription status:&#39;, error);<br>      setLoader(false);<br>    }<br>  };</pre><p><strong>Make the purchase</strong></p><pre> const makingPurchase = async () =&gt; {<br>    setLoader(true);<br>    try {<br>      const paymentResult = await InAppPurchasePayments(SKU_IDs);<br>      if (paymentResult.success) {<br>//Success call your required functions here.<br>        setLoader(false);<br>      } else {<br>        Alert.alert(t(&#39;PaymentFailed&#39;));<br>        setLoader(false);<br>      }<br>    } catch (error) {<br>      setLoader(false);<br>      Alert.alert(error);<br>      console.log(&#39;Payment error:&#39;, error);<br>    }<br>  };</pre><p><strong>Reference: </strong><a href="https://react-native-iap.dooboolab.com/docs/get-started">react-native-iap</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2cde60309c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How React Native Keeps Location Tracking Active After App Termination]]></title>
            <link>https://medium.com/@salmankn033/how-react-native-keeps-location-tracking-active-after-app-termination-5bd138574a33?source=rss-3304baff9666------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd138574a33</guid>
            <dc:creator><![CDATA[Salman Khan]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 22:15:55 GMT</pubDate>
            <atom:updated>2024-02-05T23:42:58.380Z</atom:updated>
            <content:encoded><![CDATA[<p>In the dynamic landscape of mobile applications, maintaining continuous location tracking in React Native is a crucial aspect of various functionalities, such as real-time navigation, geofencing, and personalized content delivery. Developers often face the challenge of ensuring seamless location monitoring, even when users close or minimize the application.</p><p>The need for persistent location tracking arises from the growing demand for personalized and context-aware services. Applications catering to fitness, transportation, social networking, and emergency services, among others, heavily rely on accurate and up-to-date location data. However, when users exit or terminate an application, conventional methods of location tracking often cease to operate.</p><p>This tutorial addresses the intricate task of implementing background location tracking, specifically focusing on scenarios where the application is killed or running in the background. The goal is to empower developers to create applications that not only function in the foreground but also continue to provide valuable location data when users are not actively engaged with the app.</p><p>Ensuring a seamless user experience requires overcoming challenges associated with background execution, device resource management, and maintaining user privacy. By understanding the intricacies of background location tracking, developers can unlock new possibilities for location-based features and enhance the overall utility of their applications.</p><p>Throughout this tutorial, we will explore techniques to update and transmit the user’s location at regular intervals, even in scenarios where the application is not actively in use. This knowledge is invaluable for developers aiming to create robust, location-aware applications that deliver timely and relevant information to users, irrespective of their interaction status with the application.</p><h3>Prerequisites</h3><p>Before we begin, ensure that your development machine has the following installed:</p><ul><li>Node.js (v10 or later)</li><li>React Native CLI</li><li>Android Studio (for Android development)</li><li>Xcode (for iOS development)</li></ul><h3>Step 1: Install the necessary packages</h3><p>Firstly, let’s install the required packages for tracking the user’s location in the Foreground service and scheduling a background task.</p><p>For iOS, background location tracking is handled by `react-native-geolocation-service`, while for Android, an additional package, `@supersami/rn-foreground-service`, is required.<br> Execute the following commands in your terminal to install the packages:</p><pre>npm i @supersami/rn-foreground-service<br>npm i react-native-geolocation-service</pre><p>Packages references<br>Reference: <a href="https://rn-foreground.vercel.app/">https://rn-foreground.vercel.app/</a></p><p>Reference: <a href="https://github.com/Agontuk/react-native-geolocation-service/">https://github.com/Agontuk/react-native-geolocation-service/</a></p><h3>Set 2: IOS setup for react-native-geolocation-service</h3><h4>1) Linking</h4><p>For RN 0.60 or higher, no manual linking is needed. After installing the package, just run pod installs from inside the ios directory. It’ll automatically pick up the package and install it.</p><h4>2) Enable Swift Support</h4><p>Since the iOS implementation is written in Swift, you need to add Swift support to your project. It can be done just by adding an empty swift file and a bridging header in your project folder. You have to do it from Xcode, otherwise swift compiler flag won’t be updated.</p><ul><li>Select File -&gt; New -&gt; File from Xcode</li><li>Choose a Swift file, name it anything</li><li>Click Next and say yes when prompted if you’d like to generate a bridging header (important)</li></ul><h3>Step 3: Android setup for <a href="https://github.com/Agontuk/react-native-geolocation-service/">react-native-geolocation-service</a></h3><h4>1) Linking</h4><p>For RN 0.60 or higher, no manual linking is needed. You can override the following gradle properties from your root build. gradle file.</p><pre>ext {<br>compileSdkVersion = 28<br>buildToolsVersion = &quot;28.0.3&quot;<br>minSdkVersion = 16<br>targetSdkVersion = 28<br>// Any of the following will work<br>googlePlayServicesVersion = &quot;17.0.0&quot;<br>// playServicesVersion = &quot;17.0.0&quot;<br>// playServicesLocationVersion = &quot;17.0.0&quot;<br>}</pre><h3>Step 4: Linking of @supersami/rn-foreground-service in android</h3><h4>Auto linking:</h4><p>Just run this command once and see the magic.</p><pre>node node_modules/@supersami/rn-foreground-service/postinstall.js</pre><p>In any case, if the above doesn’t link your application correctly, you can try manual linking of the application.</p><h4>Manual Linking</h4><h4><strong>* In the MainActivity file, Inside the activity tag, Paste the following:</strong></h4><pre>&lt;meta-data<br>android:name=&quot;com.supersami.foregroundservice.notification_channel_name&quot;<br>android:value=&quot;Sticky Title&quot;<br>/&gt;<br>&lt;meta-data<br>android:name=&quot;com.supersami.foregroundservice.notification_channel_description&quot;<br>android:value=&quot;Sticky Description.&quot;<br>/&gt;<br>&lt;meta-data<br>android:name=&quot;com.supersami.foregroundservice.notification_color&quot;<br>android:resource=&quot;@color/blue&quot;<br>/&gt;<br>&lt;service android:name=&quot;com.supersami.foregroundservice.ForegroundService&quot;&gt;&lt;/service&gt;<br>&lt;service android:name=&quot;com.supersami.foregroundservice.ForegroundServiceTask&quot;&gt;&lt;/service&gt;</pre><p><strong>* Inside the Resource folder -&gt; Value, Create a file name colors.xml and paste the below.</strong></p><pre>&lt;resources&gt;<br>&lt;item name=&quot;blue&quot; type=&quot;color&quot;&gt;#00C4D1<br>&lt;/item&gt;<br>&lt;integer-array name=&quot;androidcolors&quot;&gt;<br>&lt;item&gt;@color/blue&lt;/item&gt;<br>&lt;/integer-array&gt;<br>&lt;/resources&gt;</pre><h3>Step 5: Link the Package:</h3><p>Most React Native packages need to be linked to your project. Run the following command to link the installed package:</p><p><strong>I. Navigate to the android directory and clean</strong></p><pre>cd android &amp;&amp; ./gradlew clean</pre><p><strong>II. Navigate to the ios directory and install pods</strong></p><pre>cd ios &amp;&amp; pod install - repo-update</pre><p>If you are using a library that does not require linking, follow its specific instructions.</p><p><strong>Step 5: Permission In ios:</strong><br>There are three info.plist keys for location service</p><p>III. Add the following permissions in info.plist</p><pre>&lt;key&gt;NSLocationAlwaysAndWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;App needs AlwaysAndWhenIn BG locations permission&lt;/string&gt;<br>&lt;key&gt;NSLocationAlwaysUsageDescription&lt;/key&gt;<br>&lt;string&gt;App needs Always BG locations permission&lt;/string&gt;<br>&lt;key&gt;NSLocationWhenInUseUsageDescription&lt;/key&gt;<br>&lt;string&gt;App needs BG locations permission&lt;/string&gt;</pre><p>These permissions enable the app to access the device’s location even when the app is running in the background or the screen is locked.</p><p><strong>IV. Add location update to Xcode</strong></p><ol><li>Go to Xcode and open your project target.</li><li>Go to Signing &amp; Capabilities -&gt; Capability add Background Modes</li><li>select the Location update.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bgEIeUW_pMQN6iBw" /></figure><h3>Step 6: Permissions in Android :</h3><p>Next, we need to grant the necessary permissions to access the device’s location.</p><p>Add the following uses-permission in AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.ACCESS_BACKGROUND_LOCATION&quot; /&gt;</pre><h3><strong>Step 7: Initialize and Configure in JavaScript:</strong></h3><p>In your React Native JavaScript code, initialize and configure the background tracking library. This typically involves setting up event listeners, configuring options, and starting the tracking service. Here’s a simplified example:</p><pre>import { StyleSheet, Text, View, PermissionsAndroid, Button, Alert } from &#39;react-native&#39;;<br>import React, { useEffect } from &#39;react&#39;;<br>import Geolocation from &#39;react-native-geolocation-service&#39;;<br>import ReactNativeForegroundService from &quot;@supersami/rn-foreground-service&quot;;<br>const App = () =&gt; {<br>useEffect(() =&gt; {<br>requestLocationPermission();<br>updateForeground();<br>Notification();<br>startTracking();<br>// Clear watch position when the component unmounts<br>return () =&gt; {<br>Geolocation.clearWatch(watchId);<br>};<br>}, []);<br>let watchId = null;<br>const requestLocationPermission = async () =&gt; {<br>try {<br>const granted = await PermissionsAndroid.request(<br>PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,<br>{<br>title: &#39;Location Permission&#39;,<br>message: &#39;App needs access to your location.&#39;,<br>buttonNeutral: &#39;Ask Me Later&#39;,<br>buttonNegative: &#39;Cancel&#39;,<br>buttonPositive: &#39;OK&#39;,<br>},<br>);<br>if (granted === PermissionsAndroid.RESULTS.GRANTED) {<br>console.log(&#39;Location permission granted&#39;);<br>} else {<br>console.log(&#39;Location permission denied&#39;);<br>}<br>const backgroundGranted = await PermissionsAndroid.request(<br>PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,<br>{<br>title: &#39;Background Location Permission&#39;,<br>message: &#39;We need access to your location for background tracking.&#39;,<br>buttonNeutral: &#39;Ask Me Later&#39;,<br>buttonNegative: &#39;Cancel&#39;,<br>buttonPositive: &#39;OK&#39;,<br>},<br>);<br>if (backgroundGranted === PermissionsAndroid.RESULTS.GRANTED) {<br>console.log(&#39;Background location permission granted&#39;);<br>} else {<br>console.log(&#39;Background location permission denied&#39;);<br>}<br>} catch (err) {<br>console.warn(err);<br>}<br>};<br>const updateForeground = () =&gt; {<br>ReactNativeForegroundService.add_task(() =&gt; startTracking(), {<br>delay: 100,<br>onLoop: true,<br>taskId: &quot;taskid&quot;,<br>onError: (e) =&gt; console.log(`Error logging:`, e),<br>});<br>};<br>const Notification = () =&gt; {<br>ReactNativeForegroundService.start({<br>id: 1244,<br>title: &#39;Location Tracking&#39;,<br>message: &#39;Location Tracking&#39;,<br>icon: &#39;ic_launcher&#39;,<br>button: false,<br>button2: false,<br>setOnlyAlertOnce: true,<br>color: &#39;#000000&#39;,<br>});<br>};<br>const startTracking = async () =&gt; {<br>watchId = Geolocation.watchPosition(<br>position =&gt; {<br>let x = [position.coords.longitude, position.coords.latitude];<br>console.warn(&quot;xxxjjj&quot;, Platform.OS, x);<br>},<br>error =&gt; {<br>console.log(&#39;maperror in getting location&#39;, error.code, error.message);<br>},<br>{ enableHighAccuracy: true, distanceFilter: 0 },<br>);<br>};<br>return (<br>&lt;View style={{ justifyContent: &#39;center&#39;, alignItems: &#39;center&#39;, flex: 1 }}&gt;<br>&lt;Text style={{ color: &#39;red&#39;, fontWeight: &#39;600&#39;, fontSize: 20, margin: 30 }}&gt;Location Tracking&lt;/Text&gt;<br>&lt;Button onPress={Notification} title=&#39;Start Tracking&#39; /&gt;<br>&lt;/View&gt;<br>);<br>};<br>export default App;<br>const styles = StyleSheet.create({});</pre><p>Adjust the configuration based on your app’s requirements and the capabilities provided by the chosen library.</p><p>Source Code: <a href="https://github.com/Salmankhan033/React-Native-BackgroundLocation">https://github.com/Salmankhan033/React-Native-BackgroundLocation</a></p><p>Video Example:</p><p><a href="https://drive.google.com/file/d/1A9oF3kmTIdv04UwHLLILu1KrK0wYBv8P/view?usp=sharing">WhatsApp Video 2024-02-06 at 3.13.01 AM.mp4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd138574a33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>