【发布时间】:2015-12-08 01:33:47
【问题描述】:
现在我正在做一个应用程序项目,需要我的 iPhone 扫描附近的其他蓝牙设备并列出它们。我想知道我的代码有什么问题吗?
代码:
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate {
var manager: CBCentralManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CBCentralManager (delegate: self, queue: nil)
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("Peripheral: \(peripheral)")
}
func centralManagerDidUpdateState(central: CBCentralManager) {
print("Checking")
switch(central.state)
{
case.Unsupported:
print("BLE is not supported")
case.Unauthorized:
print("BLE is unauthorized")
case.Unknown:
print("BLE is Unknown")
case.Resetting:
print("BLE is Resetting")
case.PoweredOff:
print("BLE service is powered off")
case.PoweredOn:
print("BLE service is powered on")
print("Start Scanning")
manager.scanForPeripheralsWithServices(nil, options: nil)
default:
print("default state")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我使用的是 iPhone 5 (iOS 9),我确定我的蓝牙已打开。
当我在 iPhone 中运行应用程序时,控制台只记录以下输出:
Checking
BLE service is powered on
Start Scanning
但是输出中没有显示蓝牙设备的名称。即使我打开我的 iPad (iPad Mini 4 iOS 8),列表仍然不会更新。
有时它会扫描我的 MacBook Pro 蓝牙并且输出会是这样的:
Peripheral: <CBPeripheral: 0x14d70e00, identifier = 54738076-6C97-FD04-18CF-5E1AF6705865, name = vivien’s MacBook Pro, state = disconnected>
那么,为什么会这样呢?谁能给我解释一下?
【问题讨论】:
-
如果 ipad 上没有运行作为 BLE 外围设备的应用程序,那么您的应用程序将找不到任何东西。您可以使用 LightBlue 应用宣传心率监测器等外围设备
-
@Paulw11 正如你所说,当我在 LightBlue 应用程序中添加虚拟外围设备时,我的 iPhone 能够扫描我的 iPad。如果删除虚拟外围设备,则无法再次扫描我的 iPad。我以为所有的手机、平板电脑都是外围设备,不是吗?那么,要启用扫描其他 iPhone 和 iPad,我需要在后台运行 LightBlue 应用程序吗?
-
为了省电iOS只在需要的时候做广告;即当应用程序正在宣传外围设备时
-
@Paulw11 所以无论如何我仍然需要在后台运行 LightBlue 应用程序,对吧?还是有其他办法?
-
嗯,您需要在后台添加一些应用广告,才能让您的设备被发现
标签: ios iphone swift ipad bluetooth