這是我知道了:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSArray *peripheralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothPeripheralsKey];
if (peripheralManagerIdentifiers) {
// We've restored, so create the _manager on the main queue
_manager = [[CBPeripheralManager alloc] initWithDelegate:self
queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
options:@{CBPeripheralManagerOptionRestoreIdentifierKey:@"YourUniqueIdentifier"}];
} else {
// Not restored so just create as normal
manager = [[CBPeripheralManager alloc] initWithDelegate:self
queue:nil
options:@{CBPeripheralManagerOptionRestoreIdentifierKey:@"YourUniqueIdentifier"}];
}
return YES;
}
然後:
- (void)peripheralManager:(CBPeripheralManager *)peripheral
willRestoreState:(NSDictionary *)dict
{
// This is the advertisement data that was being advertised when the app was terminated by iOS
_advertisementData = dict[CBPeripheralManagerRestoredStateAdvertisementDataKey];
NSArray *services = dict[CBPeripheralManagerRestoredStateServicesKey];
// Loop through the services, I only have one service but if you have more you'll need to check against the UUID strings of each
for (CBMutableService *service in services) {
_primaryService = service;
// Loop through the characteristics
for (CBMutableCharacteristic *characteristic in _primaryService.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID]) {
_primaryCharacteristic = characteristic;
NSArray *subscribedCentrals = characteristic.subscribedCentrals;
// Loop through all centrals that were subscribed when the app was terminated by iOS
for (CBCentral *central in subscribedCentrals) {
// Add them to an array
[_centrals addObject:central];
}
}
}
}
}
藍牙行爲有時很奇怪。這也發生在我身上,重新啓動設備,突然它工作。此外,您的應用程序在被殺之前最後一件事情可能需要掃描或嘗試連接外設。 – Yazid
雖然您需要再次實例化中央管理器,否則willRestoreState:將不會被調用。 – OutOnAWeekend