ios 保证蓝牙在app生命周期内一直在后台运行

关于ios蓝牙开发请见我的另一篇博客:http://my.oschina.net/OSChinaKANON/blog/401851

现在ios和蓝牙连接时关于蓝牙的操作我想大致应该就是放在ViewController和AppDelegate中。如果app中只是某个页面需要连接蓝牙并获得数据,那蓝牙委托代理可以直接放在该ViewController中,网上大多demo都这样,操作都比较简洁。但是如果app中多个页面都需要获取蓝牙数据,这时候还将蓝牙委托代理放在ViewController中的话,需要将数据进行存储,sqlite或者CoreData都可以,但是别的页面再向存储容器中去取数据,虽然可行,但显然比较麻烦。所以我想介绍下AppDelegate中设置蓝牙的代理:

如果觉得将所有的委托函数都写在AppDelegate中显得臃肿的话,可以自己封装一层,推荐个开源APi:BabyBluetooth。

将委托设置在Appdelegate中

  //NSMutableArray *peripherals;

  //初始化BabyBluetooth 蓝牙库

    baby = [BabyBluetooth shareBabyBluetooth];

    //设置蓝牙委托

    [self babyDelegate];

   //详见BabyBluetooth

//蓝牙网关初始化和委托方法设置

-(void)babyDelegate{

    

    //__weak typeof(self) weakSelf = self;

    __weak typeof(self) weakSelf = self;

    [baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {

        if (central.state == CBCentralManagerStatePoweredOn) {

            [SVProgressHUD showInfoWithStatus:@"设备打开成功,开始扫描设备"];

            [weakSelf StartScan];

        }

    }];

    

    //设置扫描到设备的委托

    [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {

        NSLog(@"搜索到了设备:%@",peripheral.name);

       Myperipheral=peripheral;

        if ([peripheral.name isEqualToString:@"YK661DM20A"]) {

             Myperipheral=peripheral;

            [weakSelf StartdiscoverServices:peripheral];

        }

        //[weakSelf insertTableView:peripheral];

    }];

    //设置设备连接成功的委托

    [baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {

        NSLog(@"设备:%@--连接成功",peripheral.name);

        //Myperipheral=peripheral;

        //[weakSelf StartdiscoverServices];

    }];

    //设置设备连接失败的委托

    [baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {

        NSLog(@"设备:%@--连接失败",peripheral.name);

    }];

    //设置设备断开连接的委托

    [baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {

        NSLog(@"设备:%@--断开连接",peripheral.name);

    }];

    

    //设置发现设备的Services的委托

    [baby setBlockOnDiscoverServices:^(CBPeripheral *peripheral, NSError *error) {

        for (CBService *service in peripheral.services) {

            NSLog(@"搜索到服务:%@",service.UUID.UUIDString);

            [weakSelf insertSectionToTableView:service];

        }

    }];

    //设置发现设service的Characteristics的委托

    [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {

        

            for (CBCharacteristic *c in service.characteristics) {

                NSLog(@"charateristic name is :%@",c.UUID);

            }

        [weakSelf insertRowToTableView:service];

    }];

    //设置读取characteristics的委托

    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {

        NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);

    }];

    //设置发现characteristics的descriptors的委托

    [baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {

        NSLog(@"===characteristic name:%@",characteristic.service.UUID);

        for (CBDescriptor *d in characteristic.descriptors) {

            NSLog(@"CBDescriptor name is :%@",d.UUID);

        }

    }];

    //设置读取Descriptor的委托

    [baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {

        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);

    }];

    

    //设置查找设备的过滤器

    [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName) {

        

        //设置查找规则是名称大于1 , the search rule is peripheral.name length > 2

        if ([peripheralName isEqualToString:@"YK661DM20A"]) {

            return YES;

        }

        return NO;

    }];

}

下面是我利用BabyBluetooth封装的一些方法,用语蓝牙的初始化/扫描/连接/发送命令/监听&&接收数据

-(void)BleInit{

    //初始化其他数据 init other

    peripherals = [[NSMutableArray alloc]init];

    

    //初始化BabyBluetooth 蓝牙库

    baby = [BabyBluetooth shareBabyBluetooth];

    //设置蓝牙委托

    self.services = [[NSMutableArray alloc]init];

    [self babyDelegate];


}

-(void)StartScan{

    //停止之前的连接

    [baby cancelAllPeripheralsConnection];

    //设置委托后直接可以使用,无需等待CBCentralManagerStatePoweredOn状态。

    baby.scanForPeripherals().begin();

}

-(void)StartdiscoverServices:(CBPeripheral*)Per{

    baby.having(Per).and.connectToPeripherals().and.discoverServices().and.discoverCharacteristics().begin();

}

-(void)Record{

    CBCharacteristic *recordBuf =  [BabyToy findCharacteristicFormServices:self.services UUIDString:@"xxxxxx"];

//设置要监听的服务特征值

    if (recordBuf) {

        [Myperipheral setNotifyValue:YES forCharacteristic:recordBuf];

    }

}

-(void)SendStart{

    NSString *value=@"xxxxxxxxx";

// 设置要发送的命令(开始发送数据)

    NSData *data = [self dataWithHexstring:value];

    CBCharacteristic *currentCharacteristic = [BabyToy findCharacteristicFormServices:self.services UUIDString:@"xxxxxxxx"];

//设置要发送的服务特征值

    [Myperipheral writeValue:data forCharacteristic:currentCharacteristic type:CBCharacteristicWriteWithResponse];

}

-(void)SendEnd{

    NSString *value=@"xxxxxxxx";

// 设置要发送的命令(停止发送数据)

    NSData *data = [self dataWithHexstring:value];

    CBCharacteristic *currentCharacteristic = [BabyToy findCharacteristicFormServices:self.services UUIDString:@"xxxxxxxxx"];

//设置要发送的服务特征值

    [Myperipheral writeValue:data forCharacteristic:currentCharacteristic type:CBCharacteristicWriteWithResponse];

}

到此为止,Appdelegate设置基本完成,扫描和连接可以放在Appdelegate中完成,接下来可以在其他ViewController中调用AppDelegate方法来设置蓝牙发送和停止发送数据,其他的操作其实也可以添加。

//@property(nonatomic) AppDelegate *delegate;

   //监听蓝牙并发送命令给蓝牙使开始发送数据

    delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];

    [delegate Record];

    [delegate SendStart];

//@property(nonatomic) AppDelegate *delegate;

   //监听蓝牙并发送命令给蓝牙使停止发送数据

    delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];

    [delegate Record];

    [delegate SendEnd];

利用Appdelegate保证蓝牙在后台运行通讯的方法大概这样,欢迎大家讨论!


转载于:https://my.oschina.net/OSChinaKANON/blog/511344

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值