Giter VIP home page Giter VIP logo

mrousavy / react-native-google-nearby-messages Goto Github PK

View Code? Open in Web Editor NEW
202.0 3.0 32.0 1.19 MB

📲 Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!

Home Page: https://mrousavy.github.io

License: MIT License

Java 6.48% JavaScript 7.43% Starlark 2.98% Ruby 5.86% Objective-C 7.58% TypeScript 24.67% Swift 16.10% Kotlin 28.90%
react-native android ios native-module google nearby nearby-messages api library typescript

react-native-google-nearby-messages's Introduction

react-native-google-nearby-messages

An async Google Nearby Messages API Wrapper for React Native (Android & iOS), supporting autolinking, custom discovery modes (broadcast, scan, ..), custom discovery mediums (bluetooth, audio, ..), awaitable native invokations and React hooks!

Also, this is a good example on how to use Swift in a React Native - Native Module.

react-native-google-nearby-messages GitHub stars GitHub followers

Buy Me a Coffee at ko-fi.com

Install

This packages uses React Native autolinking (> 0.60)

npm i react-native-google-nearby-messages
# for iOS
cd ios && pod install && cd ..

Note (iOS): Everytime you run pod install an entry called Assets.car is created in your Build Phases -> [CP] Copy Pods Resources which causes the build to fail. This is a known bug in the Google NearbyMessages pod. A workaround is to manually remove this file everytime you run pod install. See #4 (comment) for an automatic fix. Please create a PR here if you found a better solution for this!

Usage

See the example app.

iOS Setup

See: https://developers.google.com/nearby/messages/ios/get-started

  1. Add bluetooth permissions (NSBluetoothPeripheralUsageDescription, NSBluetoothAlwaysUsageDescription for 'ble', and NSMicrophoneUsageDescription for 'audio') to Info.plist
  2. Create your API Key at the Google Developer Console.
  3. (Optionally): Add the react-native-permissions library to check if Bluetooth is available on the device (it's 'unavailable' on iOS Simulators!) If it's 'unavailable', calls to subscribe or publish might crash the app (EXC_BAD_ACCESS) so only call if Bluetooth permission is denied, granted or blocked. This library will handle the permission checking for you when you call publish() or subscribe() for the first time.
  4. Pass the generated API Key as a parameter using the connect function

Android Setup

See: https://developers.google.com/nearby/messages/android/get-started

  1. Create your API Key at the Google Developer Console.

  2. Add your generated API Key and Permissions to your AndroidManifest.xml:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.google.sample.app" >
        <!-- For BLE/Bluetooth -->
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
        <!-- For Audio -->
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
        <application ...>
            <meta-data
                android:name="com.google.android.nearby.messages.API_KEY"
                android:value="API_KEY" />
            <activity>
            ...
            </activity>
        </application>
    </manifest>
  3. (Optionally): Call checkBluetoothAvailability() to ensure that Bluetooth capabilities are available on the current device.

  4. Call connect without any key.

Publishing

import { connect, publish, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unpublish = await publish('hello !');

// later, e.g. in componentWillUnmount()
removeListener();
unpublish();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Subscribing

import { connect, subscribe, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unsubscribe = await subscribe(
  (m) => {
    console.log(`new message found: ${m}`);
  },
  (m) => {
    console.log(`message lost: ${m}`);
  });

// later, e.g. in componentWillUnmount()
removeListener();
unsubscribe();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Bluetooth Availability

Check if the user has granted Bluetooth Permissions. This feature is experimental, and strongly differs between iOS and Android.

import { checkBluetoothPermission } from 'react-native-google-nearby-messages';

const hasPermission = await checkBluetoothPermission();

Check if bluetooth is available on this device. This feature is experimental, and strongly differs between iOS and Android. Make sure to use a library like react-native-permissions to check if Bluetooth is really available, otherwise your Application might crash with a EXEC_BAD_ACCESS error. See troubleshooting

import { checkBluetoothAvailability } from 'react-native-google-nearby-messages';

const isBluetoothAvailable = await checkBluetoothAvailability();

React Hooks

This library also provides react hooks for common use cases. In case you're not familiar with hooks, please read the hooks documentation. When the component unmounts, the hooks automatically stop publishing, subscribing, remove error listeners and disconnect for you. You can also look into the hooks source code and tweak them for your use case.

Make sure to memoize the NearbyConfig object using useMemo, otherwise the hooks will fall into an infinite loop of re-renders because the config object gets re-created each time and therefore has changed. (See: react useEffect's deps)

useNearbyPublication

Publishes a message and returns a state which describes the Nearby API status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const nearbyStatus = useNearbyPublication(nearbyConfig, 'Hello from Nearby!');
  // ...
}

useNearbySubscription

Subscribe to nearby messages and return a state for all messages in an array, as well as a state describing the Nearby API Status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { nearbyMessages, nearbyStatus } = useNearbySubscription(nearbyConfig);
  return (
    <FlatList
      data={nearbyMessages}
      renderItem={({ item }) => <Text>{item}</Text>}
      />
  );
}

useNearbySearch

Search for a specific message using nearby messages. The isNearby local specifies whether the string iPhone 11 could be found using the Nearby API, and the nearbyStatus local describes the current status of the Nearby API. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { isNearby, nearbyStatus } = useNearbySearch(nearbyConfig, 'iPhone 11');
  return (
    <Text>{isNearby ? 'iPhone 11 is nearby!' : 'iPhone 11 is far, far away.'}</Text>
  );
}

useNearbyErrorCallback

Subscribe to any errors emitted from the Nearby API.

export default function App() {
  useNearbyErrorCallback((kind, message) => {
    console.log(`Nearby API Error: ${kind}: ${message}`)
  });
}

Troubleshooting

If you're having any trouble getting the Nearby API working, please make sure you've read the Troubleshooting Page.

If that doesn't help either, create an issue.

Buy Me a Coffee at ko-fi.com

Resources

react-native-google-nearby-messages's People

Contributors

0xpetra avatar dependabot-preview[bot] avatar leviwilliams avatar mrousavy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-google-nearby-messages's Issues

Check if Bluetooth is available

Problem

When trying to call connect() and publish()/subscribe() on a device that doesn't support Bluetooth (react-native-permissions returns 'unavailable'), for example the iOS Simulator, the App just exits with a EXEC_BAD_ACCESS error.

Solution

Add a safe availability check before calling the Nearby API. Unfortunately the Nearby API doesn't provide a function for that, only a has permission check (bool)... Maybe use CoreBluetooth?

Notes

On Android it works by calling the UNSUPPORTED_ERROR event.

Duplicate Resources (Assets.car)

Problem

The Google Nearby Pod adds the Assets.car file to Build Phases -> [CP] Copy Pods Resources in the Apps .xcodeproj file, which makes building impossible, as another Assets.car resource is already defined, meaning they would overwrite eachother.
This is a known issue of the Google Nearby API, but I'm sure there are easy workarounds for that such as a post_install Podfile hook. Problem is I don't know ruby.

Solution

Add a post_install Podfile hook?

[QUESTION] Why unpublish() is not declared as async in index.ts ?

Question

Hello Marc,

Why unpublish() is not declared as async in index.ts while in https://github.com/mrousavy/react-native-google-nearby-messages/blob/master/android/src/main/java/com/mrousavy/nearby/GoogleNearbyMessagesModule.kt#L191 it is declared as async?
I mean if I call publish() right after unpublish(), the unpublish might still be in progress, right?
Thanks

Environment

paste the output of `react-native info` here
"react": PASTE_VERSION_HERE,
"react-native": PASTE_VERSION_HERE,
"react-native-google-nearby-messages": PASTE_VERSION_HERE

[BUG] IllegalArgumentException on Android [ConnectionResult=APP_NOT_OPTED_IN]

IllegalArgumentException on Android [ConnectionResult=APP_NOT_OPTED_IN]

I have read the Troubleshooting page: Yes

Describe the bug
When calling connect, I get this Exception in the Logs and the Nearby API is not working:

GMS core API Availability. ConnectionResult=2802, tag=null
 java.lang.IllegalArgumentException
at com.google.android.gms.common.GoogleApiAvailability.zae(com.google.android.gms:play-services-base@@18.0.1:2)
at com.google.android.gms.common.GoogleApiAvailability.zah(com.google.android.gms:play-services-base@@18.0.1:6)
at com.google.android.gms.common.api.internal.GoogleApiManager.zaG(com.google.android.gms:play-services-base@@18.0.1:1)
at com.google.android.gms.common.api.internal.zabq.zar(com.google.android.gms:play-services-base@@18.0.1:21)
at com.google.android.gms.common.api.internal.zabq.onConnectionFailed(com.google.android.gms:play-services-base@@18.0.1:1)
at com.google.android.gms.common.internal.zai.onConnectionFailed(com.google.android.gms:play-services-base@@18.0.1:1)
at com.google.android.gms.common.internal.zzf.zzb(com.google.android.gms:play-services-basement@@18.1.0:2)
at com.google.android.gms.common.internal.zza.zza(com.google.android.gms:play-services-basement@@18.1.0:3)
at com.google.android.gms.common.internal.zzc.zze(com.google.android.gms:play-services-basement@@18.1.0:3)
at com.google.android.gms.common.internal.zzb.handleMessage(com.google.android.gms:play-services-basement@@18.1.0:31)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.os.HandlerThread.run(HandlerThread.java:67)

According to NearbyMessagesStatusCodes the error code 2802 refers to

public static final int APP_NOT_OPTED_IN
Status code indicating that the User has not granted the calling application permission to use Nearby.Messages.
Resolution: The application can use the returned PendingIntent to request user consent.
Constant Value: 2802

Environment

Additional context
I changed the kotlin version in build.gradle to "1.6.0" as the app wouldn't build otherwise.
I tried all kinds of combinations of permissions in AndroidManifest and requesting these with react-native-permissions:

  • BLUETOOTH
  • BLUETOOTH_ADMIN
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION
  • BLUETOOTH_SCAN
  • BLUETOOTH_ADVERTISE
  • BLUETOOTH_CONNECT
"react": "18.1.0",
"react-native": "0.70.6",
"react-native-google-nearby-messages": "1.0.22"

I hope you have an idea to solve this issue. It's working fine on iOS. Thanks!

[QUESTION] Can this work with two android emulators on the same computer?

Question

I'll probably give this a test on my own but maybe this is a question that someone else might have and, thus, it may be good for the search algorithms. But effectively my question is...

Can this work with two android emulators on the same computer?

So apparently it's not too much of a burden to run multiple emulator instances. See here. Another question is you can do the same for iphone but after a quick search it, either no one has tried it, you can't or it isn't talked about alot. But I don't know because I haven't tried. I don't know why android studio and android sdk weren't found since I'm able to test locally but whatever.

Environment

System:
    OS: Linux 5.15 Ubuntu 20.04.3 LTS (Focal Fossa)
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 7.93 GB / 31.07 GB
    Shell: 5.0.17 - /bin/bash
  Binaries:
    Node: 16.13.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 8.3.1 - /usr/local/bin/npm
    Watchman: Not Found
  SDKs:
    Android SDK: Not Found
  IDEs:
    Android Studio: Not Found
  Languages:
    Java: 11.0.13 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.2 => 17.0.2 
    react-native: 0.66.4 => 0.66.4 
  npmGlobalPackages:
    *react-native*: Not Found
{
  "react": "17.0.2",
  "react-native": "0.66.4",
  "react-native-google-nearby-messages": "none"
}

plugin with id 'maven' not found

Question

When using the package with Expo the command eas build --profile development --platform android fails with a series of warnings and errors.

Expo doctor:

Running "expo doctor"
- Finding all copies of expo-modules-autolinking
- Finding all copies of @expo/config-plugins
[stderr] [20:13:25] Expected package @expo/config-plugins@^5.0.0
[stderr] [20:13:25] Found invalid:
[stderr] [20:13:25]   @expo/[email protected]
[stderr] [20:13:25]   (for more info, run: npm why @expo/config-plugins)
- Finding all copies of @expo/prebuild-config
- Finding all copies of @unimodules/core
- Finding all copies of @unimodules/react-native-adapter
- Finding all copies of react-native-unimodules
Command "expo doctor" failed.
bash exited with non-zero code: 1

Gradlew:

[stderr] FAILURE: Build completed with 2 failures.
[stderr] 1: Task failed with an exception.
[stderr] -----------
[stderr] * Where:
[stderr] Build file '/home/expo/workingdir/build/node_modules/react-native-google-nearby-messages/android/build.gradle' line: 24
[stderr] * What went wrong:
[stderr] A problem occurred evaluating project ':react-native-google-nearby-messages'.
[stderr] > Plugin with id 'maven' not found.
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] A problem occurred configuring project ':react-native-google-nearby-messages'.
[stderr] > compileSdkVersion is not specified. Please add it to build.gradle
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] * Get more help at https://help.gradle.org
[stderr] BUILD FAILED in 1m 49s
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.3.3/userguide/command_line_interface.html#sec:command_line_warnings
6 actionable tasks: 6 executed
Error: Gradle build failed with unknown error. See logs for the "Run gradlew" phase for more information.

This instead is the plugin that I implemented according to the package requests:

  const { AndroidConfig, withAndroidManifest } = require("@expo/config-plugins");
  const { addMetaDataItemToMainApplication, getMainApplicationOrThrow } =
    AndroidConfig.Manifest;
  
  module.exports = withMyCustomConfig = (config) => {
    return withAndroidManifest(config, async (config) => {
      // Modifiers can be async, but try to keep them fast.
      config.modResults = await setCustomConfigAsync(config, config.modResults);
      return config;
    });
  };
  
  // Splitting this function out of the mod makes it easier to test.
  async function setCustomConfigAsync(config, androidManifest) {
    const appId = "my-app-id";
    // Get the <application /> tag and assert if it doesn't exist.
    const mainApplication = getMainApplicationOrThrow(androidManifest);
  
    addMetaDataItemToMainApplication(
      mainApplication,
      // value for `android:name`
      "com.google.android.nearby.messages.API_KEY",
      // value for `android:value`
      "myabikey"
    );
  
    return androidManifest;
  }

I honestly have no idea if this is the correct implementation, help would be very welcome. Thanks in advance.

Environment

"react": 18.1.0,
"react-native": 0.70.5,
"react-native-google-nearby-messages": 1.0.22

Communication between iOS and Android devices is broken

Question

Transmitting data from ios to android is not working
(iOS to iOS) (Android - Android) (Android - iOS) is working fine
Attached google issue tracker - https://issuetracker.google.com/issues/176461658?pli=1

Why communication is hot happening

Environment

info Fetching system and libraries information...
(node:6925) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
System:
    OS: macOS 11.1
    CPU: (4) x64 Intel(R) Core(TM) i5-8210Y CPU @ 1.60GHz
    Memory: 152.55 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 14.17.6 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.14.15 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 14.2, DriverKit 20.0, macOS 11.0, tvOS 14.2, watchOS 7.1
    Android SDK:
      API Levels: 23, 28, 29, 30, 31
      Build Tools: 29.0.2, 30.0.2, 30.0.3, 31.0.0
  IDEs:
    Android Studio: 2020.3 AI-203.7717.56.2031.7678000
    Xcode: 12.2/12B45b - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0 
    react-native: 0.61.5 => 0.61.5 
  npmGlobalPackages:
    react-native-cli: 2.0.1
    react-native-haptic-feedback: 1.11.0
    react-native: 0.63.4
"react": 16.9.0,
"react-native": 0.61.5,
"react-native-google-nearby-messages": 1.0.20

Implement lifecycle management

Problem

When the Activity/UIView gets destroyed, the Google Nearby Messages object stays active (I think). Meaning: Published messages stay published, Subscriptions emit found/lost events and other events like Errors still get emitted.

Solution

Call unsubscribe and unpublish in Activity/UIView pauses, and re-subscribe and re-publish (with the same message) again in resume. On Activity/UIView destroy, unpublish, unsubscribe and disconnect (destroy objects, remove listeners, ..)

Android has these functions in the LifecycleEventListener, see the GoogleNearbyMessagesModule.kt file, at the bottom. On iOS I have no idea, I think an invalidate method would be called when the UIView gets destroyed.

Resources

this S/O thread

[QUESTION] Check if nearby service is allowed on the device

Question

Currently when a user wants to use the nearby service, he needs to allow it from the google services notification. Is there a way to check in the app if the user has accepted the service and if he has not done so to show him an alert dialog, where he can accept it.

Environment

"react": 17.0.2,
"react-native": 0.66.4,
"react-native-google-nearby-messages": 1.0.22

[BUG] If Device A publishes again after initial load, it disconnects from Device B

Bug

I have read the Troubleshooting page: Yes

Describe the bug
When I try to publish a stringified object on Device A after it published on the initial load, it seems to drop Device A's connection with Device B

To Reproduce
Steps to reproduce the behavior:

  1. Publish a stringified object on the device A, and see from device B that Device A has dropped

Expected behavior
Device A and Device B should remain connected after the subsequent publish

Logs

iOS:

2020-10-12 21:15:37.826 [info][tid:main][RCTRootView.m:294] Running application example ({
    initialProps =     {
    };
    rootTag = 1;
})
2020-10-12 21:15:37.854188-0700 example[8814:1181360] [] nw_socket_handle_socket_event [C3.1:1] Socket SO_ERROR [61: Connection refused]
2020-10-12 21:15:37.855988-0700 example[8814:1181360] [] nw_socket_handle_socket_event [C3.2:1] Socket SO_ERROR [61: Connection refused]
2020-10-12 21:15:37.856414-0700 example[8814:1181355] [] nw_connection_get_connected_socket [C3] Client called nw_connection_get_connected_socket on unconnected nw_connection
2020-10-12 21:15:37.856450-0700 example[8814:1181355] TCP Conn 0x280751800 Failed : error 0:61 [61]
2020-10-12 21:15:38.453 [info][tid:com.facebook.react.JavaScript] Running "example" with {"rootTag":1,"initialProps":{}}
2020-10-12 21:15:38.486759-0700 example[8814:1181346] [] nw_socket_handle_socket_event [C5:1] Socket SO_ERROR [61: Connection refused]
2020-10-12 21:15:38.488500-0700 example[8814:1181352] [] nw_connection_get_connected_socket [C5] Client called nw_connection_get_connected_socket on unconnected nw_connection
2020-10-12 21:15:38.488556-0700 example[8814:1181352] TCP Conn 0x280755ec0 Failed : error 0:61 [61]
GNM_BLE: Checking Bluetooth Permissions...
GNM_BLE: CBCentralManager did update state with 5
2020-10-12 21:15:38.511386-0700 example[8814:1181360] [CoreBluetooth] XPC connection invalid
2020-10-12 21:15:38.513 [info][tid:com.facebook.react.JavaScript] Connecting...
GNM_BLE: Connecting...
2020-10-12 21:15:38.517 [info][tid:com.facebook.react.JavaScript] Connected!
2020-10-12 21:15:38.517 [info][tid:com.facebook.react.JavaScript] Subscribing...
GNM_BLE: Subscribing...
2020-10-12 21:15:38.519 [info][tid:com.facebook.react.JavaScript] Subscribed!
2020-10-12 21:15:38.521 [info][tid:com.facebook.react.JavaScript] Publishing "Alex’s iPhone"...
GNM_BLE: Publishing...
2020-10-12 21:15:38.521 [info][tid:com.facebook.react.JavaScript] Published "Alex’s iPhone"!
2020-10-12 21:15:39.863897-0700 example[8814:1181352] [CoreBluetooth] API MISUSE: <CBCentralManager: 0x281944540> has no restore identifier but the delegate implements the centralManager:willRestoreState: method. Restoring will not be supported
2020-10-12 21:15:39.866164-0700 example[8814:1181353] [CoreBluetooth] WARNING: <CBPeripheralManager: 0x28034c000> has no restore identifier but the delegate implements the peripheralManager:willRestoreState: method. Restoring will not be supported
2020-10-12 21:15:39.867249-0700 example[8814:1181353] [CoreBluetooth] API MISUSE: <CBPeripheralManager: 0x28034c000> can only accept this command while in the powered on state
GNM_BLE: Found message!
GNM_BLE: Found message!
2020-10-12 21:15:52.049 [info][tid:com.facebook.react.JavaScript] Found: {"deviceName":"iPod touch","text":"Useless Placeholder"}
2020-10-12 21:15:52.060 [info][tid:com.facebook.react.JavaScript] Found: {"deviceName":"iPod touch"}
2020-10-12 21:15:58.749705-0700 example[8814:1181198] [Snapshotting] Snapshotting a view (0x109f08180, _UIReplicantView) that has not been rendered at least once requires afterScreenUpdates:YES.
2020-10-12 21:16:00.531677-0700 example[8814:1181360] [general] Connection to daemon was invalidated
GNM_BLE: Publishing...
(this is when device gets "lost")

React Native:

[Mon Oct 12 2020 21:15:50.501]  LOG      Running "example" with {"rootTag":1,"initialProps":{}}
[Mon Oct 12 2020 21:15:50.502]  LOG      Connecting...
[Mon Oct 12 2020 21:15:50.502]  LOG      Connected!
[Mon Oct 12 2020 21:15:50.503]  LOG      Subscribing...
[Mon Oct 12 2020 21:15:50.503]  LOG      Subscribed!
[Mon Oct 12 2020 21:15:50.503]  LOG      Publishing "iPod touch"...
[Mon Oct 12 2020 21:15:50.503]  LOG      Published "iPod touch"!
[Mon Oct 12 2020 21:15:52.550]  LOG      Found: {"deviceName":"iPod touch","text":"Useless Placeholder"}
[Mon Oct 12 2020 21:15:52.710]  LOG      Found: {"deviceName":"iPod touch"}
[Mon Oct 12 2020 21:15:52.278]  LOG      Found: {"deviceName":"Alex’s iPhone"}
[Mon Oct 12 2020 21:16:06.916]  LOG      Found: {"deviceName":"Alex’s iPhone","text":"Moo"}
[Mon Oct 12 2020 21:16:06.919]  LOG      Lost: "{\"deviceName\":\"Alex’s iPhone\"}"
"react": 16.11.0 ,
"react-native": 0.62.2,
"react-native-google-nearby-messages": 0.10.20

Background Usage

This is more of a feature request/question. I've been looking into using this library to still detect devices while running in the background. Obviously I could register a headless component for android but this does not work in iOS. We would have to write a native iOS bridge to stay cross-platform and support this running in the background.

I do not have much experience in this and thus I'm wondering if this is even a possible addition to this library. Or if it's even possible to do some other way? I know native apps use nearby messages in the background normally. Would love to hear your thoughts.

Permissions Error Android

Currently have been trying to get this library working on Android with no luck. First thing I discovered is that if google play services is out of date the addOnErrorListener will return a permissions error and the app will crash. Even if the app has full permissions. Often (but not every time) on first load the app will prompt the user to give the app correct permissions if they have not already been granted, then the same error will persist again.

Also, if the app is downloaded and given full permissions before first load then the app will send subscribe/publish once. Then on reload of the app it will no longer work and persist the same error as the first time.

I have followed the troubleshooting guide for Android. The api key is correct (and working because it works on first load) and permissions are given yet I cannot get it to work on Android. Have you had any similar issues?

Device: Huawei P20 Lite running Android 9.

StackOverflow onFound - android

Hello,

I followed the setup from the example project to send a message from ios to android on 2 real devices and got a stackoverflow on the android device:

java.lang.StackOverflowError: stack size 8MB
	at com.mrousavy.nearby.GoogleNearbyMessagesModule$connect$1.onFound(Unknown Source:2)
	at com.mrousavy.nearby.GoogleNearbyMessagesModule$connect$1.onFound(GoogleNearbyMessagesModule.kt:65)
	at com.mrousavy.nearby.GoogleNearbyMessagesModule$connect$1.onFound(GoogleNearbyMessagesModule.kt:65)
	...

On ios everything seems fine.

I'm using "react-native-google-nearby-messages": "^1.0.14"

The code:

const [nearbyMessage, setNearbyMessage] = React.useState('');

    useNearbyErrorCallback(
        React.useCallback((kind, message) => {
            Alert.alert(kind, message);
        }, []),
    );

    const _connect = React.useCallback(async () => {
        console.log('Connecting...');
        await connect({
            apiKey: config.iosNearbyDeviceApiKey,
            discoveryModes: ['broadcast', 'scan'],
            discoveryMediums: ['ble'],
        });
        console.log('Connected!');
        return () => disconnect();
    }, []);
    const _publish = React.useCallback(async () => {
        const deviceName = await getDeviceName();
        console.log(`Publishing "${deviceName}"...`);
        await publish(deviceName);
        console.log(`Published "${deviceName}"!`);
    }, []);
    const _subscribe = React.useCallback(async () => {
        console.log('Subscribing...');
        await subscribe(
            (m) => {
                setNearbyMessage(m);
                console.log(`Found: ${JSON.stringify(m)}`);
            },
            (m) => {
                setNearbyMessage('');
                console.log(`Lost: ${JSON.stringify(m)}`);
            },
        );
        console.log('Subscribed!');
    }, []);
    const _checkPermissions = React.useCallback(async () => {
        const permission = await checkBluetoothPermission();
        const available = await checkBluetoothAvailability();
        Alert.alert(
            'Bluetooth Permissions:',
            `Granted: ${permission}, Available: ${available}`,
        );
    }, []);

    React.useEffect(() => {
        const start = async () => {
            try {
                await _checkPermissions();

                await _connect();
                await _subscribe();
                await _publish();
            } catch (e) {
                Alert.alert(
                    'Unknown error occured while connecting!',
                    JSON.stringify(e.message ?? e),
                );
            }
        };

        start();
        return () => disconnect();
    }, [_connect, _subscribe, _publish, _checkPermissions]);

Functional Component Usage

Hey,

Thanks for creating this package its a lifesaver. It would be super helpful if you could post examples in the documentation of usage inside of an app that utilizes functional components with hooks. Been using your example to try to build it but I think the flow is confusing to convert to without any insight. Setting the event listeners in useEffect along with the flow of checking permissions with the permissions library mentioned in the docs.

More of a documentation/example enhancement than an issue.

Thanks!

`new NativeEventEmitter()` was called with a non-null argument without the required `removeListeners` method.

Support other discovery modes

Problem

Currently only .BLE is supported as a discovery mode. The Nearby API also supports .Audio (on Android it also differs between .BLE and .Bluetooth).

Solution

Add an enum (typescript OR type) to select the discovery mode for the native API. On the Native side, either define those strings and switch between ("ble", "audio", "both", "default"?), create an NSEnum, or use Integers and map those.

Need to work this Google Nearby Feature Without Internet and wifi

"react": "16.11.0",
"react-native": "0.62.2",
"react-native-google-nearby-messages": latest

My functionality is working when internet connection available, but without internet, it is not working.
I write down those codes in react native. Now I have two iPhones.
So please tell me how this SDK will be work without the internet.

what this library do

i install this library with example
and i don't know what can i do in this library

please explain or give me link for more details

Edit
i run this example on tow device and discovered
but what i can do after that

[FEATURE] onBLESignalChanged and onDisctanceChanged

Problem

I have seen the old repository react-native-nearby-api which has onBLESignalChanged and onDisctanceChanged to get the distance between devices. I couldn't find it in this projekt and would realy like to use it. Is there any chance it gets implemented soon?

[BUG] Not working in background job (https://www.npmjs.com/package/react-native-background-job)

Bug

I have read the Troubleshooting page: Yes

Describe the bug
I'm using this library with https://www.npmjs.com/package/react-native-background-job, if app opens everting is fine, while background mode, it's not able to connect

To Reproduce
Steps to reproduce the behavior:

  1. install react-native-background-job
  2. schedule a job
  3. call connect method
  4. See error
"react": 16.12,
"react-native": 0.61.5,
"react-native-google-nearby-messages": 1.0.20

2 duplicate symbols architecture arm64 (unless I use a pod post-install script)

Here's the error:

duplicate symbol 'google::RemoveLogSink(google::LogSink*)' in:
    /Users/ryantremblay/ReLearnApp/ios/Pods/NearbyMessages/Libraries/libGNSMessages.a(logging.o)
    /Users/ryantremblay/Library/Developer/Xcode/DerivedData/ReLearn-dkmyfsbkdgxjzccgsexwkuiqxsnz/Build/Products/Debug-iphoneos/glog/libglog.a(logging.o)
duplicate symbol 'google::AddLogSink(google::LogSink*)' in:
    /Users/ryantremblay/ReLearnApp/ios/Pods/NearbyMessages/Libraries/libGNSMessages.a(logging.o)
    /Users/ryantremblay/Library/Developer/Xcode/DerivedData/ReLearn-dkmyfsbkdgxjzccgsexwkuiqxsnz/Build/Products/Debug-iphoneos/glog/libglog.a(logging.o)
ld: 2 duplicate symbols for architecture arm64

This is resolved by using this script:

post_install do |installer|
  

  puts "Renaming logging functions"

  root = File.dirname(installer.pods_project.path)
  Dir.chdir(root);
  Dir.glob("**/*.{h,cc,cpp,in}") {|filename|
    filepath = root + "/" + filename
    text = File.read(filepath)
    addText = text.gsub!(/(?<!React)AddLogSink/, "ReactAddLogSink")
    if addText
      File.chmod(0644, filepath)
      f = File.open(filepath, "w")
      f.write(addText)
      f.close
    end

    text2 = addText ? addText : text
    removeText = text2.gsub!(/(?<!React)RemoveLogSink/, "ReactRemoveLogSink")
    if removeText
      File.chmod(0644, filepath)
      f = File.open(filepath, "w")
      f.write(removeText)
      f.close
    end
  }
  
   
end

Any idea why you didn't experience this?

[BUG] Compile error in Swift code

Bug

I have read the Troubleshooting page: Yes

Describe the bug
I'm trying to use the library in an Expo project using their EAS build tool (which lets you add third party native modules) and I get the following error while compiling the pod:

Screen Shot 2022-01-05 at 3 39 30 PM

Any idea why I could be getting this error? Do I need to be compiling against a certain version of the iOS APIs or something like that? Thanks for any help, because I really need to get this working.

Fix missing override keyword

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessages.swift b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessages.swift
index 8035174..06dbe6f 100644
--- a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessages.swift
+++ b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessages.swift
@@ -231,7 +231,7 @@ class NearbyMessages: RCTEventEmitter {
 
 	// Called when the UIView gets destroyed (e.g. App reload)
 	@objc
-	func invalidate() {
+    override func invalidate() {
 		print("GNM_BLE: invalidate")
 		disconnect()
 	}
diff --git a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.h b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.h
index ce3c532..b0ca220 100644
--- a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.h
+++ b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.h
@@ -3,8 +3,8 @@
 //
 
 #import <Foundation/Foundation.h>
-#import "RCTBridgeModule.h"
-#import "RCTEventEmitter.h"
+#import <React/RCTBridgeModule.h>
+#import <React/RCTEventEmitter.h>
 #import "GNSMessages.h"
 
 @interface GoogleNearbyMessagesBridge: NSObject
diff --git a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.m b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.m
index 17c67f8..a56f633 100644
--- a/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.m
+++ b/node_modules/react-native-google-nearby-messages/ios/GoogleNearbyMessagesBridge.m
@@ -7,8 +7,8 @@
 //
 
 #import "GoogleNearbyMessagesBridge.h"
-#import "RCTBridgeModule.h"
-#import "RCTEventEmitter.h"
+#import <React/RCTBridgeModule.h>
+#import <React/RCTEventEmitter.h>
 
 @interface RCT_EXTERN_REMAP_MODULE(GoogleNearbyMessages, NearbyMessages, NSObject)
 

This issue body was partially generated by patch-package.

[QUESTION]

Question

Is there any way to get this to work with Expo? With the latest Expo SDK, it's possible to use native modules without ejecting, but I can't seem to get this library to work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.