使用iPhone作为iBeacon发射器

时间:2016-02-28 09:18:48

标签: ios swift swift2 ibeacon

我试图设置我的iPhone来播放iBeacon信号,让另一部iPhone拿起来。那个应该接收信号的iPhone正在工作,但我无法通过其他iPhone来播放信号。

我遵循本教程:https://www.hackingwithswift.com/example-code/location/how-to-make-an-iphone-transmit-an-ibeacon

这是我的代码:

import CoreBluetooth
import CoreLocation

class iBeaconTransmission: NSObject, CBPeripheralManagerDelegate {

    var localBeacon: CLBeaconRegion!
    var beaconPeripheralData: NSDictionary!
    var peripheralManager: CBPeripheralManager!

    func initLocalBeacon() {
        if localBeacon != nil {
            stopLocalBeacon()
        }

        let localBeaconUUID = "placeholder"
        let localBeaconMajor: CLBeaconMajorValue = 123
        let localBeaconMinor: CLBeaconMinorValue = 456

        let uuid = NSUUID(UUIDString: localBeaconUUID)!
        localBeacon = CLBeaconRegion(proximityUUID: uuid, major: localBeaconMajor, minor: localBeaconMinor, identifier: "placeholder")

        self.beaconPeripheralData = self.localBeacon.peripheralDataWithMeasuredPower(nil)
        self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
    }

    func stopLocalBeacon() {
        peripheralManager.stopAdvertising()
        peripheralManager = nil
        beaconPeripheralData = nil
        localBeacon = nil
    }

    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
        print("Peripheral Manager")
        if peripheral.state == .PoweredOn {
            print("Transmitting")
            peripheralManager.startAdvertising(beaconPeripheralData as! [String: AnyObject]!)
        } else if peripheral.state == .PoweredOff {
            peripheralManager.stopAdvertising()
        }
    }
}

另一方面,位置服务已设置为始终授权。

"周边经理"也永远不会被打印出来,因此出于某种原因不会被调用的功能。

谢谢!

1 个答案:

答案 0 :(得分:0)

固定。我将代码移动到视图控制器中,并在viewDidLoad函数中调用了initLocalBeacon()。