藍牙打印小票

//藍牙搜索的類

@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 - 藍牙狀態(tài)

-(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 @"刪除";

}

/*刪除用到的函數(shù)*/

-(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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市寂殉,隨后出現(xiàn)的幾起案子滓侍,更是在濱河造成了極大的恐慌际歼,老刑警劉巖耗绿,帶你破解...
    沈念sama閱讀 211,123評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蝶溶,死亡現(xiàn)場離奇詭異吓妆,居然都是意外死亡赊时,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評論 2 384
  • 文/潘曉璐 我一進店門行拢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來祖秒,“玉大人,你說我怎么就攤上這事舟奠〗叻欤” “怎么了?”我有些...
    開封第一講書人閱讀 156,723評論 0 345
  • 文/不壞的土叔 我叫張陵沼瘫,是天一觀的道長抬纸。 經常有香客問我,道長耿戚,這世上最難降的妖魔是什么湿故? 我笑而不...
    開封第一講書人閱讀 56,357評論 1 283
  • 正文 為了忘掉前任阿趁,我火速辦了婚禮,結果婚禮上坛猪,老公的妹妹穿的比我還像新娘脖阵。我一直安慰自己,他們只是感情好墅茉,可當我...
    茶點故事閱讀 65,412評論 5 384
  • 文/花漫 我一把揭開白布命黔。 她就那樣靜靜地躺著,像睡著了一般就斤。 火紅的嫁衣襯著肌膚如雪悍募。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,760評論 1 289
  • 那天洋机,我揣著相機與錄音搜立,去河邊找鬼。 笑死槐秧,一個胖子當著我的面吹牛,可吹牛的內容都是我干的忧设。 我是一名探鬼主播刁标,決...
    沈念sama閱讀 38,904評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼址晕!你這毒婦竟也來了膀懈?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,672評論 0 266
  • 序言:老撾萬榮一對情侶失蹤谨垃,失蹤者是張志新(化名)和其女友劉穎启搂,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體刘陶,經...
    沈念sama閱讀 44,118評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡胳赌,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,456評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了匙隔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疑苫。...
    茶點故事閱讀 38,599評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖纷责,靈堂內的尸體忽然破棺而出捍掺,到底是詐尸還是另有隱情,我是刑警寧澤再膳,帶...
    沈念sama閱讀 34,264評論 4 328
  • 正文 年R本政府宣布挺勿,位于F島的核電站,受9級特大地震影響喂柒,放射性物質發(fā)生泄漏不瓶。R本人自食惡果不足惜禾嫉,卻給世界環(huán)境...
    茶點故事閱讀 39,857評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望湃番。 院中可真熱鬧夭织,春花似錦、人聲如沸吠撮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽泥兰。三九已至弄屡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鞋诗,已是汗流浹背膀捷。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留削彬,地道東北人全庸。 一個月前我還...
    沈念sama閱讀 46,286評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像融痛,于是被迫代替她去往敵國和親壶笼。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,465評論 2 348

推薦閱讀更多精彩內容