这两个概念可以用传统的模式client-server来理解,central意思是中心其作用类似server; periperal就是外设,一般携带有数据,我们需要去其中获取数据,下图是苹果官网的例子,peripheral是心跳仪,按期作用,我们去这个外设中取心跳数据,则心跳仪的作用就类似server了,我们的手机去心跳仪中获取数据,类似client。
在介绍代码之前我导入了以上框架
在serverViewController.m 的代码如下:
#import "serverViewController.h"
//generated by command "uuidgen" 这是我的两个蓝牙UUID
static NSString *const kServiceUUID = @"DDDD4D86-502A-4F58-B747-347B186F6812";
static NSString *const kCharacteristicUUID = @"6A6201D6-CEAA-4714-8CF2-DBF471874321";
@interface ViewController ()
//周边管理者
@property (nonatomic , strong) CBPeripheralManager *peripheralManager;
@property (nonatomic , strong) CBMutableCharacteristic *customCharacteristic;
@property (nonatomic , strong) CBMutableService *customService;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}
//上面代码这里我们创建了一个CBCentralManager,用来发现外设
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - 私有函数
- (void)setupService
{
//creates the characteristic UUID
CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
//create the characteristic
self.customCharacteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUUID
properties:CBCharacteristicPropertyNotify
value:nil
permissions:CBAttributePermissionsReadable];
//create the service UUID
CBUUID *servieceUUID = [CBUUID UUIDWithString:kServiceUUID];
//creates the service and adds the charecteristic to it
self.customService = [[CBMutableService alloc] initWithType:servieceUUID primary:YES];
//sets the characteristics for this service
[self.customService setCharacteristics:@[self.customCharacteristic]];
//publishs the service
[self.peripheralManager addService:self.customService];
}
#pragma mark -
#pragma mark - CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary *)dict
{
NSLog(@"%s,dict = %@",__PRETTY_FUNCTION__,dict);
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
if (error == nil) {
//starts advertising the service
[self.peripheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey:@"服务门店",