请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - CoreBluetooth "willRestoreState"- 究竟应该在那里做什么?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 16:59:37 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在开发一个需要持续运行和跟踪一些外围特征的应用程序。

在前台一切正常。
它也可以在后台运行,但我不确定我是否正确。

我发了很多关于状态恢复和实现 willRestoreState 的帖子,但其中很多都没有明确告诉你当这个方法被调用时该怎么做。

我正在做的过程是这样的:

我正在使用

创建一个中央管理器
myCentralManager =
        [[CBCentralManager alloc] initWithDelegate:self queue:nil
         options{ CBCentralManagerOptionRestoreIdentifierKey:
         @"myCentralManagerIdentifier" }];

从这里开始,我正在执行以下常规流程:
等待中央管理器开机(centralManagerDidUpdateState) -> 扫描我的外围设备 -> 连接到它 -> 发现服务 -> 发现特征 -> 订阅特征 -> 读取数据

然后我杀死我的应用程序使用

kill(getpid(), SIGKILL);

我正在等待几秒钟,然后再次从我的外围设备开始做广告。

然后我可以看到进程恢复了生命,并且我的日志显示 AppDelegate 中的 didFinishLaunchingWithOptions 被调用。

然后我像这样恢复中央管理器:

 NSArray *identifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];

   if (identifiers && identifiers.count > 0) {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                               queue:nil
                                                             options{CBCentralManagerOptionRestoreIdentifierKey:[identifiers objectAtIndex:0]}];
    } 

我还可以看到 willRestoreStatecentralManagerDidUpdateState 正在被调用。

这就是我迷路的地方。 接下来我该怎么办?如果我继续进行常规流程(我在上面描述过,所有似乎都可以正常工作 - 并且以与上述相同的方式。

但是 - 我做对了吗?

我应该在 willRestoreState 中做些什么吗? 如果是,我应该怎么做?

提前致谢!



Best Answer-推荐答案


基本上,您将返回已连接的外围设备 - 您应该保存对它的引用并将自己设置为它的委托(delegate)。这是我的代码,非常简单:

   - (void)centralManagerCBCentralManager *)central willRestoreStateNSDictionary<NSString *,id> *)dict
 {
      //get the handle to the peripheral already connected by the os and set ourselves as the delegate
      NSArray *peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey];
      if (peripherals.count > 0){
        CBPeripheral* pr = peripherals[0];
        // Set peripheral required values and start discovering services
        [pr setDelegate:self];
        [pr readRSSI];
        [pr discoverServices:nil];
      }
}

关于ios - CoreBluetooth "willRestoreState"- 究竟应该在那里做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37796780/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap