gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:50 26 4
gpt4 key购买 nike

我想用 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 使用 Core Bluetooth 是一个严重的限制。而这些其他东西需要关闭我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com