IOS蓝牙搜索列表之Masonry布局显示UITableView

  • 通过之前学习的经验总结,这个月公司需要利用IOS原生做蓝牙设备搜索,以及后续的链接,读取,写入描述!
  • 主要就分为以下重点部分:

1,蓝牙设备列表的搜索;
2,扫描外围设备;
3,扫描到的蓝牙设备添加到devices数组中,刷新列表;
4,蓝牙连接成功时候的代理;
5,蓝牙连接失败时候的代理;
6,蓝牙连接断开时候的代理;
7,利用第三方框架Masonry布局把蓝牙列表Name显示UITableView上;

开始实际操作,看代码:

一:ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) UITableView *tableView;

@end

二:ViewController.m(重点蓝牙部分代码,在这个文件里面哦)

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "TableviewCellTableViewCell.h"
#import "Masonry.h"
@interface ViewController ()<CBCentralManagerDelegate, UITableViewDelegate,UITableViewDataSource>{
    UITableViewCell *cell;
}

@property (nonatomic,strong ) CBCentralManager *manager;// 中心设备
@property (nonatomic,strong ) NSMutableArray   <CBPeripheral*>*devices;// 扫描到的外围设备
@property (nonatomic, strong) NSMutableArray   *connectSuccess;//链接成功的的外设

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    self.tableView.frame = self.view.bounds;

    //创建蓝牙管理者对象
    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.devices = [NSMutableArray array];
    self.connectSuccess = [NSMutableArray array];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

//中心设备状态改变的代理必须实现
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state)
    {
        case CBManagerStatePoweredOn:
            NSLog(@"蓝牙已打开");
            [_manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : [NSNumber numberWithBool:YES]}];
            //            [self showInfo:@"蓝牙已打开"];
            break;
        case CBManagerStateUnknown:
            //            [self showInfo:@"蓝牙 状态位置"];
            break;
        case CBManagerStatePoweredOff:
            NSLog(@"蓝牙未打开");

            //            [self showInfo:@"蓝牙未打开"];
            break;
        case CBManagerStateResetting:
            //            [self showInfo:@"蓝牙初始化中"];
            break;
        case CBManagerStateUnsupported:
            NSLog(@"蓝牙不支持状态");

            //            [self showInfo:@"蓝牙不支持状态"];
            break;
        case CBManagerStateUnauthorized:
            //            [self showInfo:@"蓝牙设备未授权"];
            break;
        default:
            break;
    }
}


- (IBAction)startScan:(id)sender {
    //扫描外设
    NSLog(@"scan....");

    [self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];
    //3秒后停止。(开启扫描后会不停的扫描)
    [self performSelector:@selector(stopScan) withObject:nil afterDelay:5];
}

/**
 *  停止扫描
 */
-(void)stopScan{
    [self.manager stopScan];
    NSLog(@"stopScan....");
}

//扫描到的蓝牙设备添加到devices数组中,刷新列表
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    if (![self.devices containsObject:peripheral]) {
        [self.devices addObject:peripheral];

        [self.tableView reloadData];
        NSLog(@"发现外围设备:%@---RSSI:%@---advertisementData:%@",peripheral,RSSI,advertisementData);
    }
}

/**
 *  蓝牙连接成功时候的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前连接的设备
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"%@名字的蓝牙连接成功",peripheral.name);
    cell.detailTextLabel.text = @"已连接";
    [self.connectSuccess addObject:peripheral];

}
/**
 *  蓝牙链接失败的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前连接的外设
 *  @param error      错误信息
 */
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{

    NSLog(@"%@名字的蓝牙连接失败",peripheral.name);
}
/**
 *  蓝牙断开连接的代理
 *
 *  @param central    中心设备
 *  @param peripheral 当前需要断开连接的外设
 *  @param error      错误信息
 */
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"%@名字的蓝牙断开链接",peripheral.name);
    cell.detailTextLabel.text = @"";
    for (int i=0;i<_connectSuccess.count;i++) {
        if ([peripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
            [self.connectSuccess removeObject:peripheral];
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.manager connectPeripheral:self.devices[indexPath.row] options:nil];
    cell = [tableView cellForRowAtIndexPath:indexPath];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    return self.devices.count;
    return self.devices.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";

    TableviewCellTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell1 == nil) {
        cell1 = [[TableviewCellTableViewCell alloc]
                 initWithStyle:UITableViewCellStyleValue1
                 reuseIdentifier:CellIdentifier];
    }

    if (!self.devices[indexPath.row].name) {
        cell1.username.text=@"null";
    }else{
        cell1.username.text=self.devices[indexPath.row].name;
    }
    return cell1;

}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell2 = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell2.detailTextLabel.text isEqualToString:@"已连接"]) {
        return YES;
    }
    return NO;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = [tableView cellForRowAtIndexPath:indexPath];

    UITableViewRowAction *disconnect = [UITableViewRowAction rowActionWithStyle:1 title:@"断开连接" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //断开蓝牙连接
        CBPeripheral *peripheral = self.devices[indexPath.row];
        [self.manager cancelPeripheralConnection:peripheral];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }];
    return @[disconnect];
}

@end

以上两个文件,实现了蓝牙的开启判断,搜索蓝牙列表,masonry的定义,成功链接上蓝牙的时候,失败的时候,断开蓝牙的判断,接下里就是两个UI的文件,蓝牙信息获取到了,就要显示到界面上才行!如下:

三:TableviewCellTableViewCell.h(定义一个UILabel控件,类似android里面的texeview,上面那个就类似与listview)

#import <UIKit/UIKit.h>

@interface TableviewCellTableViewCell : UITableViewCell

@property(strong,nonatomic) UILabel *username;

@end

四:TableviewCellTableViewCell.m

#import "TableviewCellTableViewCell.h"

#ifdef __OBJC__
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
#endif

@implementation TableviewCellTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

/*
 * 初始化布局
 */
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        //品牌
        self.username = [[UILabel alloc] init];
        _username.textColor = [UIColor redColor];
        _username.font = [UIFont fontWithName:@"Helvetica" size:30];
        _username.text = @"BTaaa";
        _username.textAlignment = NSTextAlignmentCenter;

        [self addSubview:_username];

        [_username makeConstraints:^(MASConstraintMaker *make){
            make.top.equalTo(self).offset(10);
            make.left.equalTo(self).offset(10);
            make.width.equalTo(@150);
            make.height.equalTo(@30);
        }];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

@end

上面这两个文件,重点阐述了UILabel的定义,以及初始化,name为控件名,布局为Masonry.h框架(这个必须要导入进去),其次就是布局的初始化文字,颜色,字体,等宽与等高…

五:此文章实现了IOS蓝牙设备获取列表,并利用第三方框架Masonry布局显示,合理的所用蓝牙知识做当今流行的智能互联网设备APP,如有疑问,可以向博主留言,若有帮助,请继续给予支持!希望可以帮助到更多的学者,谢谢!

猜你喜欢

转载自blog.csdn.net/qq_37523448/article/details/81060517