iBeacon_Tutorial

  1. 1. iBeacon Tutorial
    1. 1.1. Requirement
    2. 1.2. Peripheral
    3. 1.3. Central
      1. 1.3.1. Reference

iBeacon Tutorial

記錄實作iBeacon 溝通的過程, Beacon分為 Peripheral(提供local資訊) & Central(ex:App接收資訊並且用local push提醒使用者)
使用情境
以下記錄實作的細節

Requirement

BLE based on bluetooth 4.0. 可以在iOS5以上實作
特別要注意的是在iOS8 必須在info.plist 加上key

1
<key>NSLocationAlwaysUsageDescription</key]]><string>beacon testser</string]]>

Peripheral

建立service的細節在此

1
2
3
4
5
6
7
8
9
10
11
12
- (void)setupService
{
CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
self.customCharacteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
CBUUID *serviceUUID = [CBUUID UUIDWithString:kServiceUUID];
self.customService = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];
[self.customService setCharacteristics:@[self.customCharacteristic]];
[self.peripheralManager addService:self.customService];
}

Sample code 可以在這裡找到
流程如下

monitorBeacon

特別說明

1
2
3
4
[[CLBeaconRegion alloc] initWithProximityUUID:uuid
major:rand()
minor:rand()
identifier:@"com.beaconDemo"];

裡面的uuid可以代表公司 或者整棟百貨, Central端也是靠相同的uuid做beacon的搜尋
major可以是樓層等大範圍的ID, minor則可留給房號或是商品做分配

Central

Sample code can be found here
分為以下兩個部分

  • Monitoring & Ranging

monitorBeacon

完成後就可以在就可以在

1
2
3
4
func locationManager(manager: CLLocationManager!,
didRangeBeacons beacons: [AnyObject]!,
inRegion region: CLBeaconRegion!)

收到beacons的array, 其中index 0 的beacon是最近的
透過CLBeacon 可以得到 proximity, proximityUUID, rssi信號強度
其中proximity: immediate代表10mm, near代表 小於1m, far代表 大於1m

另外要注意iOS8特別的隱私設定
在使用CLLocationManager前要

1
2
3
if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) {
locationManager!.requestAlwaysAuthorization()
}
  • Connect Peripheral

centralManager = CBCentralManager(delegate: self, queue: nil)後可以透過

1
centralManager?.scanForPeripheralsWithServices(nil, options: nil)

找到週邊的Peripheal
這個sample很陽春的暫存了Perial 等到Central 跟Peripheral的距離在immediate
的時候做connect

1
2
3
case CLProximity.Immediate:
message = "You are in the immediate proximity of the beacon"
centralManager?.connectPeripheral(_peripheral, options: nil)

centralBeacon

Reference