我想使用 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/