ios Bluetooth 蓝牙

要理解iOS CoreBluetooth,有两个很重要的概念:Central 和 Periperal Devices

这两个概念可以用传统的模式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:@"服务门店",

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值