ios - 使用专用类用 iPhone 模拟信标

标签 ios objective-c iphone swift ibeacon

我想使用 iPhone 传输信标信号。目前它将在 Objective C 中实现,但计划稍后将其转换为 Swift,因此我也有兴趣找到在此阶段可能遇到的任何重要差异。

在一些研究中,我发现了模拟信标的一些局限性

Can I make iPhone/iPad broadcast as Eddystone Beacon?

以及使用 View Controller 以外的类时的一些问题的信息,至少在 swift

Using iPhone as iBeacon Transmitter

在最后一个链接中,我找到了使用 iPhone 模拟 iBeacon 的 Swift 教程的链接 - 代码放置在 View Controller 中,并且可以在这个地方工作。

https://www.hackingwithswift.com/example-code/location/how-to-make-an-iphone-transmit-an-ibeacon

但是,如果我希望应用程序执行一些其他操作而不仅仅是传输 BLE 信号,则使用 View Controller 中的核心蓝牙会受到严重限制。而其他这些东西需要解雇我的 Controller 。

很快我将尝试为 Objective C 创建一些工作代码,稍后为 Swift 创建一些工作代码,用于发出 BLE 信号并仍然更改可见 View Controller 。但也许有人做过类似的事情,并且能够说出是否有任何问题,就像之前提到的

最佳答案

是的,您绝对可以在 ViewController 之外的 iOS 上设置信标传输。下面是一个简单的 Swift 类,我在许多项目中都使用过它。

但是请注意,虽然您可以使用这样的类来进行广告,无论哪个 ViewController 位于前台,但如果您的整个应用程序位于后台,广告将会停止。这是 Apple iOS 的限制。请参阅here了解更多信息。

  import Foundation
  import CoreBluetooth
  import CoreLocation
  import UIKit

  class BeaconTransmitter: NSObject, CBPeripheralManagerDelegate {
    var region: CLBeaconRegion?
    var on = false
    var _peripheralManager: CBPeripheralManager?
    var peripheralManager: CBPeripheralManager {
      if _peripheralManager == nil {
        _peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
      }
      return _peripheralManager!
    }
    override init() {
      super.init()
    }

    func stop() {
      on = false
      peripheralManager.stopAdvertising()
    }

    func start(region: CLBeaconRegion) {
      on = true
      self.region = region
      startTransmitting()
    }

    func startTransmitting() {
      if let region = region {
        let peripheralData = region.peripheralData(withMeasuredPower: -59) as Dictionary
        peripheralManager.stopAdvertising()
        peripheralManager.startAdvertising(peripheralData as? [String : AnyObject])
      }
    }

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
      if(peripheral.state == .poweredOn) {
        if on {
          startTransmitting()
        }
      }
      else if(peripheral.state == .poweredOff) {
        NSLog("Bluetooth is off")
      }
      else if(peripheral.state == .unsupported) {
        NSLog("Bluetooth not supported")
      }
    }
  }

关于ios - 使用专用类用 iPhone 模拟信标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41037556/

相关文章:

ios - 混合模式 kCGBlendModeMultiply 没有正确地将图像与颜色相乘

ios - 允许 MPMoviePlayerViewController 横向播放,同时保留呈现 View Controller 的方向

iphone - iOS对象数组:在函数内部创建对象数组

ios - 我可以自动创建UIImageView实例吗?

iphone - NSManagedObjectContext 的 performBlockAndWait : not executing on the receiver's queue

ios - 如何为 iOS 创建游戏声音

objective-c - 更改 NSScrollview 中标尺的测量单位

iphone - 属性与实例变量

iphone - 隐藏 UI 导航栏中的后退按钮

ios - 条形图(创建为 CALayer)高度/边界动画