我有一个物联网设备正在发送 iBeacon 广告,并希望在我的 react-native 应用程序上检测这些信号。
我找到了这个库 react-native-kontaktio。它在 android 上运行良好,但在 ios 上它看起来不像“didDiscoverDevices”事件被触发,因为 console.log 没有出现在我的终端中。该应用程序正在运行,我没有收到任何错误消息。
要为 iOS 配置此库,我执行了以下操作:
- yarn add react-native-kontaktio
- 光盘
- 吊舱安装
我还在 info.plist 中包含了这些权限:NSBluetoothAlwaysUsageDescription、NSLocationAlwaysAndWhenInUseUsageDescription
这是我的 react-native 版本:react-native-cli:2.0.1,react-native:0.66.4。
这是适用于 android 的代码,但不适用于 iOS。
import React, {useEffect, useState} from 'react';
import {
Alert,
DeviceEventEmitter,
NativeEventEmitter,
Platform,
PermissionsAndroid,
SafeAreaView,
Text,
StyleSheet,
Button,
} from 'react-native';
import Kontakt, {KontaktModule} from 'react-native-kontaktio';
const {connect, init, startDiscovery, startScanning} = Kontakt;
const kontaktEmitter = new NativeEventEmitter(KontaktModule);
const isAndroid = Platform.OS === 'android';
const isIOS = Platform.OS === 'ios';
const App = () => {
/**
* Android Marshmallow (6.0) and above need to ask the user to grant certain permissions.
* This function does just that.
*/
const requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
{
title: 'Location Permission',
message:
'This example app needs to access your location in order to use bluetooth beacons.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
return true;
} else {
// permission denied
return false;
}
} catch (err) {
console.warn(err);
return false;
}
};
const beaconSetup = async () => {
if (isAndroid) {
// Android
const granted = await requestLocationPermission();
if (granted) {
await connect();
await startScanning();
} else {
Alert.alert(
'Permission error',
'Location permission not granted. Cannot scan for beacons',
[{text: 'OK', onPress: () => console.log('OK Pressed')}],
{cancelable: false},
);
}
} else {
// iOS
console.log('IOS', isIOS);
await init();
await startDiscovery();
}
// Add beacon listener
if (isAndroid) {
DeviceEventEmitter.addListener(
'beaconsDidUpdate',
({beacons, region}) => {
console.log('beaconsDidUpdate', beacons, region);
console.log('REGION: ', region);
console.log('BEACONS', beacons);
}
);
} else {
console.log('IOS ADD LISTENER');
kontaktEmitter.addListener('didDiscoverDevices', ({beacons}) => {
console.log('didDiscoverDevices', beacons);
console.log('IOS DISCOVERED BEACON');
});
}
};
useEffect(() => {
beaconSetup();
return () => {
DeviceEventEmitter.removeAllListeners();
};
}, []);