iOS蓝牙类APP常驻后台的实现方法,经过在苹果开发者论坛询问,以及查看苹果开发者文档,最后得出正确的方法为:
1.设置plist,蓝牙权限
2.到target-capabilities-background modes中打开use Bluetooth LE accessories选项
3.创建central manager时设置restore identifier
_bluetoothmanager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue options:@{CBCentralManagerOptionRestoreIdentifierKey : CardReadingServiceManagerRestoreIdentifier}];
4.appdelegate的didfinishlaunching方法中,如果检测到对应的key就重新创建Bluetooth manager
for (NSString *blue in centralManagerIdentifiers) { if ([blue isEqualToString:CardReadingServiceManagerRestoreIdentifier]) { [CardReadingService getInstance].bluetoothmanager = nil; [[CardReadingService getInstance] bluetoothmanager]; break; } }
5.实现Bluetooth central delegate的willRestoreState方法,开启扫描
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict { [self startScan]; [self startAccleerometer]; }
以上方法是从开发者文档中找到的,对应的链接
但是到iOS12之后,发现不能长期保持后台,不知道是不是系统又对应用后台做了限制,改进方法还在研究中。
原文地址:https://www.cnblogs.com/shenyuiOS/p/9989266.html
时间: 2024-11-05 19:42:57