Last Updated: February 25, 2016
·
887
· nathan chang

iBeacon Tutorial

iBeacon Tutorial

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

Requirement

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

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

Peripheral

建立service的細節在此

- (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 可以在這裡找到
流程如下

<a title="monitorBeacon by hsin chang, on Flickr">monitorBeacon</a>

特別說明

[[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

<a href="https://www.flickr.com/photos/hsin919/15538688501" title="monitorBeacon by hsin chang, on Flickr">monitorBeacon</a>

完成後就可以在就可以在

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前要

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

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

{% codeblock lang:swift %}
centralManager?.scanForPeripheralsWithServices(nil, options: nil)
{% endcodeblock %}

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

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

<a href="https://www.flickr.com/photos/hsin919/14920624754" title="centralBeacon by hsin chang, on Flickr">centralBeacon</a>

Reference