Using iPhone as iBeacon Transmitter

2019-07-20 13:02发布

I'm trying to set up my iPhone to broadcast an iBeacon signal for another iPhone to pick up. The iPhone that's supposed to pick up the signal is working, but I can't get the other iPhone to broadcast the signal.

I'm following this tutorial: https://www.hackingwithswift.com/example-code/location/how-to-make-an-iphone-transmit-an-ibeacon

And here's my code:

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()
        }
    }
}

Another note, location services is already set to always authorized.

"Peripheral Manager" is also never being printed, so the function that's in isn't being called for some reason.

Thanks!

1条回答
乱世女痞
2楼-- · 2019-07-20 14:01

Fixed. I moved the code into a view controller and called initLocalBeacon() in the viewDidLoad function.

查看更多
登录 后发表回答