iOS - 搜尋藍芽裝置

當開啟藍芽後, 可進行搜索藍芽裝置.

如何設定與開啟藍芽裝置請參考: 開啟藍芽

Step 1: 偵測是否已開始搜尋藍芽

1
mCBCentralManager.isScanning

Step 2: 搜尋藍芽裝置

1
mCBCentralManager.scanForPeripheralsWithServices(nil, options: nil);

Step 3: 監聽搜尋裝置

找到/發現裝置時會經由callback function返回
(CBCentralManagerDelegate potocol’s function)

1
2
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber)
}

Step 4: 停止搜尋裝置

1
mCBCentralManager.stopScan();

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import Foundation
import CoreBluetooth

class BtManager : NSObject {
var mCBCentralManager: CBCentralManager!

override init() {
super.init();
initCBCentralManager();
}

internal func initCBCentralManager() {
mCBCentralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true]);
}

func isScanning() -> Bool {
return mCBCentralManager.isScanning;
}

func startToScan() {
if (mCBCentralManager.state == CBCentralManagerState.PoweredOff) {
print("state is off");
initCBCentralManager();
} else {
if (isScanning()) {
print("state is scanning");
} else {
mCBCentralManager.scanForPeripheralsWithServices(nil, options: nil);
print("start to scan: \(isScanning())");
}
}
}

func stopScanning() {
mCBCentralManager.stopScan();
}
}

extension BtManager : CBCentralManagerDelegate {

func centralManagerDidUpdateState(central: CBCentralManager) {
switch (central.state) {
case CBCentralManagerState.PoweredOn:
print("state On");
case CBCentralManagerState.PoweredOff:
print("state Off");
case CBCentralManagerState.Unknown:
fallthrough;
default:
print("state Unknow");
}
}

func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("Device: \(peripheral.name) : \(peripheral.identifier.UUIDString)");
}
}
作者

Nick Lin

發表於

2016-07-05

更新於

2023-01-18

許可協議


評論