代码实现:
function taskTimeOut(promise, time = 10000) {
const timeoutPromise = new Promise((_resolve, reject) => {
setTimeout(() => { // 超时错误
reject({
code: 408,
message: "taskTimeOut"
});
}, time);
});
return Promise.race([promise, timeoutPromise]); // 使用 Promise.race 方法,谁先完成就返回谁的结果
}
/**
* ibeacon数据获取类
* 错误code描述:-1:没有蓝牙权限;-2:没有链接附近设备权限;-3:停止搜索蓝牙;-4:未知错误
*/
export class Ibeacon {
/**
* @private
*/
static isSeaching = true; // 是否搜索蓝牙中
static code = {
noBluetoothPermission: -1, // 没有蓝牙权限
noBluetoothScanPermission: -2, // 没有链接附近设备权限
stopSeachIBeacon: -3, // 停止搜索蓝牙
otherError: -4, // 其它错误
}
/**
* 开始搜索
* @param {string} uuids 要搜索蓝牙设备的guid,虽然这里参数key为uuid,但在ios系统下值应该是个标准的guid格式
* @param {number} timeOut 搜索超时时间
* @return {Array} 数组不是空数组就代表已搜索到信号
*/
static async start(uuids, timeOut = 10000) {
this.isSeaching = true;
await this.addlistenSysBluetooth();
await this.startSeachBeacons(uuids);
return await taskTimeOut(this.getBeaconsData(), timeOut);
}
static stop() {
this.isSeaching = false;
uni.stopBeaconDiscovery();
}
static addlistenSysBluetooth() {
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
success: () => {
resolve();
},
fail: (err) => {
console.log(err);
if (err?.code === 10001 || err?.code === 10000) {
reject({
code: this.code.noBluetoothPermission,
message: 'noBluetoothPermission'
});
}
reject({
code: this.code.otherError,
message: 'unknown'
})
}
});
})
}
// 开始搜索iBeacon设备
static startSeachBeacons(uuids) {
return new Promise((resolve, reject) => {
uni.startBeaconDiscovery({
uuids, // 要搜索设备的guid,虽然这里参数key为uuid,但在ios系统下值应该是个标准的guid格式
ignoreBluetoothAvailable: true, // 是否校验蓝牙开关,Android平台忽略此属性,iOS平台默认值为false。
success: () => {
resolve();
},
fail: (err) => {
console.log(err);
if (err?.errMsg.indexOf('fail android.permission.BLUETOOTH_SCANpermission denied') !== -1) {
reject({
code: this.code.noBluetoothScanPermission,
message: 'noBluetoothScanPermission' // 链接附近设备权限
});
}
reject({
code: this.code.otherError,
message: 'unknown'
})
}
});
})
}
static async getBeaconsData() {
try {
const res = await this.getBeacons();
if (res.beacons.length) {
return res.beacons;
}
// 递归终止条件检查
if (!this.isSeaching) {
throw {
code: this.code.stopSeachIBeacon,
message: 'stopSeachIBeacon'
};
}
return this.getBeaconsData();
} catch (error) {
throw {
code: this.code.otherError,
message: 'unknown'
};
}
}
static getBeacons() {
return new Promise((resolve, reject) => {
uni.getBeacons({
success: function(res) {
resolve(res);
},
fail: function(err) {
reject(err);
}
})
})
}
}
5 个回复
我愿你知道 (作者)
请问各位大佬,有人遇到过这问题吗?
iOSDeveloper - 专注于iOS相关领域 QQ:752562065
放截图啊
我愿你知道 (作者)
贴了代码了,定位权限已经开启了,然后直接执行Ibeacon.start()
2025-09-28 15:21
我愿你知道 (作者)
代码实现:
我愿你知道 (作者)
这个问题有大佬指导下吗?已经有客户反馈了
我愿你知道 (作者)
官方的兄弟们,如果是要等更新也麻烦回复下,我这里也好交差
iOSDeveloper
联系方式有么给你反馈一下
2025-10-22 17:35
我愿你知道 (作者)
回复 iOSDeveloper: QQ 562609987
2025-10-22 17:46
我愿你知道 (作者)
回复 iOSDeveloper: 麻烦你了,谢谢
2025-10-22 18:00