LoginSignup
3
2

More than 5 years have passed since last update.

iOSデバイスをビーコンとして利用する(CoreBluetooth::CBPeripheralManager.startAdvertising)

Posted at

iOSデバイスをiBeaconとして利用する

iOSデバイスをiBeaconとして利用するためには、アプリケーションが常にフォアグラウンドで動作しなければならない

UUID生成

ターミナルから「uuidgen」を実行

128ビットの値である近接UUID(universally unique identifier)は、特定のタイプまたは特定の組織によって発信されているものとして、1つ以上のビーコンを一意に識別

ビーコン領域作成・発信

ViewController.swift
import UIKit
import CoreLocation
import CoreBluetooth

class ViewController: UIViewController, CBPeripheralManagerDelegate {

    var myPeripheralManager: CBPeripheralManager!
    let myProximityUUID = NSUUID.init(UUIDString: "YourUUIDCreatedInTerminal")

    override func viewDidLoad() {
        super.viewDidLoad()

        myPeripheralManager = CBPeripheralManager(delegate: self, queue: nil)

    }

    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
        if peripheral.state == CBPeripheralManagerState.PoweredOn {
            let beaconRegion = CLBeaconRegion.init(proximityUUID: myProximityUUID!, major: 0, minor: 0, identifier: "com.mycompany.myregion")
            let beaconPeripheralData = NSDictionary(dictionary: beaconRegion.peripheralDataWithMeasuredPower(nil))

            myPeripheralManager.startAdvertising(beaconPeripheralData as? [String : AnyObject])
        }
    }

「YourUUIDCreatedInTerminal」はターミナルで生成したUUIDに置換
major値は、16ビットの符号なし整数で、同じUUIDを持つビーコンをグループ化するために使用(省略可)
minor値は、16ビットの符号なし整数で、同じUUIDと同じmajor値を持つビーコンを区別するために使用(省略可)
identifierは、コード中で領域を参照するための一意の文字列で、ビーコンが発信する識別情報とは無関係

ビーコン領域をUUID値のみで設定するのも珍しくない。この場合、指定されたUUIDのビーコン範囲内にデバイスが入ると、ビーコンまでの距離を測定し、近隣にある個別のビーコンに関する詳細情報を取得する。

参考情報

位置情報とマッププログラミングガイド
任意の値でのiBeaconの発信 - 逆引きSwift(iOS編)
【連載】Bluetooth LE (3) iOS デバイスを Bluetooth LE 機器にする

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2