ios - 使用 iPhone 作为 iBeacon 发射器

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

另外请注意,位置服务已设置为始终授权。

"Peripheral Manager"也从未被打印出来,因此其中的函数由于某种原因没有被调用。

谢谢!

最佳答案

已修复。我将代码移到 View Controller 中,并在 viewDidLoad 函数中调用了 initLocalBeacon()。

关于ios - 使用 iPhone 作为 iBeacon 发射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35680718/

相关文章:

带有对象参数的特定 UITextfield 的 Swift 2 addObserver

ios - 在设置中更改权限地址簿时应用程序崩溃

ios - 带有 CollectionView/TableView 输入/文本字段的 RxSwift

iOS 如何根据屏幕大小类调整 UILabel 或 UITextField 字体大小?

iOS 8 核心数据堆栈 - fatal error : found nil while unwrapping an Optional value

ios - 添加到管理对象有序集

swift - 将 xib 文件与 UIViewController 和自定义类链接

ios - 难倒重新 : Chrome iOS Behavior

ios - 如何强制应用程序更改 iOS/Objective-C 中的语言?

swift - OSX开发,Xib菜单和storyboard Window Controller如何关联?