swift - Xcode 8.0 CBCentralManager 问题

标签 swift xcode core-bluetooth ios10 xcode8

我最近下载了 Xcode 8.0 并尝试运行我之前使用核心蓝牙的项目。

我在build设置中启用了 Use Legacy Swift Language Version 以兼容 swift 2.3 一切正常,但出现了一个问题,

func centralManagerDidUpdateState(central: CBCentralManager)
{
    print("state is \(central.state.rawValue)")
    if (central.state == CBCentralManagerState.PoweredOn)
    {
        self.centralManager?.scanForPeripheralsWithServices([serviceUUID], options: nil)
    }
    else
    {
        // do something like alert the user that ble is not on
    }
}

以前 central.state 会返回 CBCentralManagerState 类型作为 int 但现在它返回 CBManagerState 所以出现错误所以我改为

 if (central.state == CBManagerState.PoweredOn)

CBManagerState 仅在 IOS 10+ 中受支持,但我想为 IOS 8.3+ 构建它,那么如何更改代码?

更新 我也将项目转换为 swift 3.0,但仍然是同样的问题,那么我如何在 ios 版本低于 10 的手机上运行这个项目?

最佳答案

最简单的方法就是使用枚举值的简写引用:

func centralManagerDidUpdateState(central: CBCentralManager)
{
    print("state is \(central.state.rawValue)")
    if (central.state == .PoweredOn)
    {
        self.centralManager?.scanForPeripheralsWithServices([serviceUUID], options: nil)
    }
    else
    {
        // do something like alert the user that ble is not on
    }

}

现在您的代码将在没有错误或警告的情况下编译,并且可以在所有目标上正常工作

关于swift - Xcode 8.0 CBCentralManager 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39606316/

相关文章:

ios - 将数据同时传输到多个外围设备 ios BLE

ios - 由于最大应用程序 ID 限制,无法调试我的应用程序

iOS 核心蓝牙 : Possible error codes

ios - 为什么我的代码不起作用? - setObject ForKey : key cannot be nil

objective-c - UIKeyboardDidShowNotification 被调用了两次

iOS - MPMoviePlayerController 无法从远程 URL 播放视频

ios - 验证 + 提交 iOS 应用程序包标识符问题

iOS 应用程序从后台连接低功耗蓝牙服务

ios - 找不到框架,链接器命令失败,退出代码为 1(使用 -v 查看调用)

ios - 带有新 ios-charts 框架新版本的条形图