蓝牙打印小票

//蓝牙搜索的类

@interface QueryPrinterViewController (){

      UITableView *_tableView;

      NSMutableArray *_dataArr;//存储所有搜索到得设备

}

@property (nonatomic,strong) CBPeripheral *peripheral;

@property (nonatomic,strong) CBCharacteristic *characteristic;

@property (nonatomic,strong) CBCentralManager *centralManager;

@end

@implementation QueryPrinterViewController

- (void)viewDidLoad {

[super viewDidLoad];

_dataArr = [[NSMutableArray alloc] init];

_charactersArr = [[NSMutableArray alloc] init];

isPrinting = YES;

//默认已连接设备

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

peripheralArr = [NSMutableArray arrayWithArray:[userDefaults valueForKey:@"havePares"]];

if (peripheralArr.count > 0) {

_haveConnectPeripherIdentify = peripheralArr[0][@"identify"];

}

self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];

[self initUI];

}

- (void)initUI {

self.navigationItem.title = @"蓝牙打印";

[self setRightButtonWithTitle:@[@"搜索设备"]];

_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEWWIDTH, VIEWHEIGHT) style:UITableViewStyleGrouped];

_tableView.sectionHeaderHeight = 0.01;

_tableView.sectionFooterHeight = 0.01;

_tableView.delegate = self;

_tableView.dataSource = self;

_tableView.backgroundColor = kBackGroundColor;

self.automaticallyAdjustsScrollViewInsets = NO;

[self.view addSubview:_tableView];

if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {

[_tableView  setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

}

if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {

[_tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];

}

//底部测试打印

UIButton *footBtn = [UIButton buttonWithType:UIButtonTypeCustom];

footBtn.frame = CGRectMake(0, VIEWHEIGHT - 114, VIEWWIDTH, 50);

[footBtn setTitle:@"测试打印" forState:UIControlStateNormal];

[footBtn setImage:[UIImage imageNamed:@"蓝牙测试打印图标"] forState:UIControlStateNormal];

footBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);

footBtn.backgroundColor = helpColor1;

footBtn.tag = 100;

[footBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:footBtn];

//当没有商品时

_notGoodsView = [[[NSBundle mainBundle] loadNibNamed:@"HPNotGoodsView" owner:nil options:nil] lastObject];

_notGoodsView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);

[_notGoodsView reloadImageName:@"无蓝牙打印设备" title:@"暂无设备,点击右上角搜索哦" btnTitle:nil];

[self.view addSubview:_notGoodsView];

}

- (void)doRightAction:(UIButton *)sender {

[self startScan];

}

- (void)startScan {

[self.centralManager stopScan];

[self.centralManager scanForPeripheralsWithServices:nil options:nil];

if (timer) {

[timer invalidate];

}

timer = [NSTimer scheduledTimerWithTimeInterval:8

target:self

selector:@selector(scanStop)

userInfo:nil

repeats:NO];

}

//停止搜索

- (void)scanStop {

[_centralManager stopScan];

[timer invalidate];

}

#pragma mark - 蓝牙状态

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

switch (central.state) {

case CBCentralManagerStateUnknown:

YMDLog(@">>>CBCentralManagerStateUnknown");

break;

case CBCentralManagerStateResetting:

YMDLog(@">>>CBCentralManagerStateResetting");

break;

case CBCentralManagerStateUnsupported:

YMDLog(@">>>CBCentralManagerStateUnsupported");

break;

case CBCentralManagerStateUnauthorized:

YMDLog(@">>>CBCentralManagerStateUnauthorized");

break;

case CBCentralManagerStatePoweredOff:

YMDLog(@">>>CBCentralManagerStatePoweredOff");

break;

case CBCentralManagerStatePoweredOn:

{

YMDLog(@">>>CBCentralManagerStatePoweredOn");

//当前蓝牙已打开

if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {

} else {

[self startScan];

}

}

break;

default:

break;

}

}

//扫描到设备会进入方法

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

YMDLog(@"Did discover peripheral. peripheral: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.identifier, advertisementData[@"kCBAdvDataServiceUUIDs"]);

if ([_haveConnectPeripherIdentify isEqualToString:peripheral.identifier.UUIDString]) {

self.peripheral = peripheral;

[self.centralManager connectPeripheral:self.peripheral options:nil];

[_centralManager connectPeripheral:peripheral  options:nil];

if ([_dataArr containsObject:peripheral]) {

[_dataArr removeObject:peripheral];

}

} else {

if (![_dataArr containsObject:peripheral]) {

[_dataArr addObject:peripheral];

}

}

[_tableView reloadData];

}

//连接到Peripherals-成功

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

[self scanStop];

//保存

uuidsArr = [[NSMutableArray alloc] init];

peripheralDic = [[NSMutableDictionary alloc] init];

peripheral.delegate = self;

[central stopScan];

[peripheral discoverServices:nil];

YMDLog(@">>>外设连接 %@\n", [peripheral name]);

}

//连接到Peripherals-失败

-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{

_characteristic = nil;

_peripheral = nil;

YMDLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);

}

//Peripherals断开连接

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{

_characteristic = nil;

_peripheral = nil;

YMDLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);

//停止扫描

[central stopScan];

//断开连接

[central cancelPeripheralConnection:peripheral];

[self startScan];

}

#pragma mark - 扫描到服务

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

{

if (error)

{

YMDLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);

return;

}

for (CBService *service in peripheral.services)

{

[peripheral discoverCharacteristics:nil forService:service];

YMDLog(@"Service found with UUID: %@", service.UUID);

}

}

//扫描到特征

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

{

if (error)

{

YMDLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);

return;

}

for (CBCharacteristic * characteristic in service.characteristics)

{

if ((characteristic.properties & CBCharacteristicPropertyWrite) && isPrinting) {

[peripheralArr removeAllObjects];

_peripheral = peripheral;

_characteristic = characteristic;

[_charactersArr addObject:characteristic];

YMDLog(@"Discovered characteristics for%@",characteristic.UUID.UUIDString);

for (CBService *servic in peripheral.services) {

[uuidsArr addObject:servic.UUID.UUIDString];

}

[peripheralDic  setObject:uuidsArr forKey:@"uuid"];

[peripheralDic setObject:peripheral.name ? peripheral.name : peripheral.identifier.UUIDString forKey:@"name"];

[peripheralDic  setObject:peripheral.identifier.UUIDString forKey:@"identify"];

_haveConnectPeripherIdentify = peripheral.identifier.UUIDString;

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[peripheralArr insertObject:peripheralDic atIndex:0];

[userDefaults setValue:peripheralArr forKey:@"havePares"];

[userDefaults synchronize];

[_dataArr removeObject:peripheral];

[_tableView reloadData];

isPrinting = NO;

[self startScan];

}

}

}

//写入成功的回调

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {

YMDLog(@"---%@---",characteristic.UUID);

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

if (peripheralArr.count > 0 || _dataArr.count > 0) {

_notGoodsView.hidden = YES;

} else {

_notGoodsView.hidden = NO;

}

return 2;

}

#pragma mark - tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if (section == 0) {

return peripheralArr.count;

} else {

return _dataArr.count;

}

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

[cell setSeparatorInset:UIEdgeInsetsZero];

}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

[cell setLayoutMargins:UIEdgeInsetsZero];

}

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellID = @"cellID";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

}

cell.textLabel.font = Font15;

cell.textLabel.textColor = blackTextColor;

if (indexPath.section == 0) {

if (peripheralArr.count > 0) {

NSMutableDictionary *perDic = peripheralArr[0];

cell.textLabel.text = perDic[@"name"];

}

} else {

CBPeripheral *per = _dataArr[indexPath.row];

if (per.name) {

cell.textLabel.text = per.name;

} else {

cell.textLabel.text = [NSString stringWithFormat:@"未知设备%ld",(long)indexPath.row];

}

}

cell.selectionStyle = UITableViewCellSelectionStyleNone;

return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

if (section == 0) {

if (peripheralArr.count > 0) {

return 40;

} else {

return 0.01;

}

} else {

if (_dataArr.count > 0) {

return 40;

} else {

return 0.01;

}

}

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

if (indexPath.section == 0) {

if (peripheralArr.count > 0) {

return 50;

} else {

return 0;

}

} else {

if (_dataArr.count > 0) {

return 50;

} else {

return 0;

}

}

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

return 0.01;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if (indexPath.section == 1) {

isPrinting = YES;

[_centralManager connectPeripheral:_dataArr[indexPath.row]  options:nil];

}

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

if (section == 0) {

if (peripheralArr.count > 0) {

return @"  默认连接的设备";

} else {

return @"";

}

} else {

if (_dataArr.count > 0) {

return @"  搜索到的设备";

} else {

return @"";

}

}

}

#pragma mark - 删除已配对设备

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

if (indexPath.section == 0) {

return UITableViewCellEditingStyleDelete;

} else {

return UITableViewCellEditingStyleNone;

}

}

/*改变删除按钮的title*/

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath

{

return @"删除";

}

/*删除用到的函数*/

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

_haveConnectPeripherIdentify = @"";

[peripheralArr removeAllObjects];

[[NSUserDefaults standardUserDefaults] setValue:peripheralArr forKey:@"havePares"];

[[NSUserDefaults standardUserDefaults] synchronize];

[tableView reloadData];

if (_peripheral) {

[_centralManager cancelPeripheralConnection:_peripheral];

}

}

#pragma mark - 测试打印

- (void)btnClick:(UIButton *)btn {

NSMutableArray *sendDataArray = [[NSMutableArray alloc] init];

[sendDataArray addObject:@"云门店打印测试:iOS"];

[sendDataArray addObject:[NSDate date]];

[sendDataArray addObject:@""];

[sendDataArray addObject:@""];

if (btn.tag == 100) {

if (_peripheral) {

for (CBCharacteristic * characteristic in _charactersArr) {

for (int i = 0; i < sendDataArray.count; i++) {

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

NSString *curPrintContent = [NSString stringWithFormat:@"%@",sendDataArray[i]];

NSString *printed = [curPrintContent stringByAppendingFormat:@"%c", '\n'];

NSData  *data= [printed dataUsingEncoding: enc];

[_peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

}

}

return;

}

}

[Utils showMsg:@"亲,蓝牙连接失败哦"];

}


github地址github.com/binghuiwb/BinkBluetooth

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容