iOS连接蓝牙打印,已用Object C实现,转NativeJS遇到问题,求解?

Object C代码,确认可以成功连接蓝牙打印机并正常打印

//

// ViewController.m

// CoreBlueToothTest

//

// Created by de.cel@163.com on 15/10/19.

// Copyright (c) 2015年 de.cel@163.com All rights reserved.

//



#import <CoreBluetooth/CoreBluetooth.h>

#import "ViewController.h"



@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>



@property (strong, nonatomic) IBOutlet UITextField *txtDeviceName;



@property (strong, nonatomic) IBOutlet UITextField *txtServiceUUID;



@property (strong, nonatomic) IBOutlet UITextField *txtCharacterUUID;





/**中心设备管理器*/

@property(strong,nonatomic) CBCentralManager *mgr;



/**所有蓝牙设备*/

@property(strong,nonatomic) NSMutableArray *peripherals;





@end



@implementation ViewController



- (void)viewDidLoad {

[super viewDidLoad];



//第一步:创建设备管理器



self.mgr=[[CBCentralManager alloc] init];

self.mgr= [self.mgr initWithDelegate:self queue:nil];

//self.mgr=[[CBCentralManager alloc] init];

self.peripherals= [NSMutableArray array]; //存放所有扫描到的外设

//self.mgr.delegate=self;



NSLog(@"%@",self.mgr);



}



//第二步:扫描蓝牙设备

- (IBAction)scan:(id)sender {



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

}





//第三步:扫描完成,发现设备,添加到设备列表中

#pragma mark - CBCentralManagerDelegate

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

{

if(![self.peripherals containsObject:peripheral]){



peripheral.delegate=self;

[self.peripherals addObject:peripheral];



NSLog(@"%@",peripheral.name);



}

}





//第四步:连接蓝牙设备

- (IBAction)connect:(id)sender {



if(self.mgr.state == CBPeripheralManagerStatePoweredOn)

{

for (CBPeripheral *peripheral in self.peripherals ) {



if([peripheral.name isEqualToString:self.txtDeviceName.text])

{

NSLog(@"%@",peripheral.name);

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

}

}

}

}



//第五步:连接成功,扫描蓝牙设备的服务

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

{

[peripheral discoverServices:nil];

}



//第六步:扫描到外设的所有服务后,筛选指定的服务,扫描该服务的特性

#pragma mark - CBPeripheralDelegate

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

{

NSArray *services=peripheral.services;

for (CBService *service in services) {

if([service.UUID isEqual:[CBUUID UUIDWithString:self.txtServiceUUID.text]])

{

[peripheral discoverCharacteristics:nil forService:service];

}

}

}

//第七步:扫描到指定服务的特性后,筛选指定的特性,进行交互

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

{

NSArray *characteristics=service.characteristics;

for (CBCharacteristic *characteristic in characteristics) {

if([characteristic.UUID isEqual:[CBUUID UUIDWithString:self.txtCharacterUUID.text]])

{



NSString *str = [NSString stringWithFormat:@"\n订单号:%@\n成交额:%@\n成交时间:%@\n\n", @"12345", @"40000",@"2015-10-20" ];

NSData *data =[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];



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

NSLog(@"开始打印.....");



}

}

}

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

{

NSLog(@"打印完成");

}





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

{

NSLog(@"已断开连接");

}



//外设管理器状态发生变化

-(void)centralManagerDidUpdateState:(CBCentralManager *)central

{

switch (central.state) {

case CBCentralManagerStatePoweredOn:



NSLog(@"central.state=CBCentralManagerStatePoweredOn");

//[self.mgr scanForPeripheralsWithServices:nil options:nil];

break;



default:

NSLog(@"状态发生变化");

break;

}

}



@end



\n

2015-11-02 16:59 添加评论 分享
已邀请:

最佳回复

0

DCloud_heavensoft

赞同来自:

更新:5+已提供蓝牙,参考http://www.html5plus.org/doc/zh_cn/bluetooth.html 注意需要最新版HBuilderX


0

huyong1978

赞同来自:

Native JS 代码,创建中央设备管理器,发现蓝牙设备

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.min.js"></script>
<link href="css/mui.min.css" rel="stylesheet" />
<script type="text/javascript" charset="utf-8">

mui.init();
var CBCentralManager = plus.ios.importClass("CBCentralManager");
var NSMutableArray = plus.ios.importClass("NSMutableArray");
var CBPeripheral = plus.ios.importClass("CBPeripheral");
var CBService = plus.ios.importClass("CBService");
var CBCharacteristic = plus.ios.importClass("CBCharacteristic");
var CBUUID = plus.ios.importClass("CBUUID");
//1.中央外设管理器
var manager = null;
var peripherals = null;
var peripheral_delegate = null;
function create(){
// 1.创建外设管理器
manager = new CBCentralManager();
peripherals = (new NSMutableArray()).init();

var delegate = plus.ios.implements("CBCentralManagerDelegate", {
"centralManagerDidUpdateState:": centralManagerDidUpdateState,
"centralManager:didDiscoverPeripheral:advertisementData:RSSI:": didDiscoverPeripheral
});

output('>>1. 中央外设管理器 CBCentralManager 创建成功<br>');
}

//2. 扫描所有外设
function scan() {
//alert('scaning....')
// 实现代理
var delegate = plus.ios.implements("CBCentralManagerDelegate", {
"centralManagerDidUpdateState:": centralManagerDidUpdateState,
"centralManager:didDiscoverPeripheral:advertisementData:RSSI:": didDiscoverPeripheral
});
manager.initWithDelegatequeue(delegate, null);
output('>>3. 开始扫描蓝牙外设....<br>');
manager.scanForPeripheralsWithServicesoptions(null, null);
}

function centralManagerDidUpdateState(central) {
var state = central.plusGetAttribute('state');
if (state == 4) {
mui.alert('请开启蓝牙');
}
output(">>2. 中央外设管理器状态 state= " + state + '<br>');
}

//第三步:扫描完成,发现设备,添加到设备列表中
function didDiscoverPeripheral(central, peripheral, advertisementData, RSSI) {
output('>>4. 发现蓝牙外设 didDiscoverPeripheral')
output('<br>central=' + JSON.stringify(central));

//为什么能发现,但获取不到蓝牙设备,以下三个值均返回 undefined
output('<br>peripheral=' + JSON.stringify(peripheral));
output('<br>advertisementData=' + JSON.stringify(advertisementData));
output('<br>RSSI=' + JSON.stringify(RSSI));
if ( !peripherals.containsObject(peripheral) ) {
if ( !peripheral_delegate ) {
var peripheral_delegate = plus.ios.implements("CBPeripheralDelegate", {
"peripheral:didDiscoverServices::": peripheraldidDiscoverServices,
"peripheral:didUpdateValueForCharacteristic:error:": peripheraldidDiscoverCharacteristicsForServiceerror,
"peripheral:didWriteValueForCharacteristic:error:": peripheraldidWriteValueForCharacteristiccharacteristicerror,
});
}
eripheral.setDelegate = peripheral_delegate;
peripherals.addObject(peripheral);
}
}

//第四步:连接蓝牙设备
function connect(devName){
if ( manager.state() == 5 ){
var len = peripherals.count();
for (var i = 0; i < len; i++) {
var item = peripherals.objectAtIndex(i);
if ( item.name() === devName ) {
manager.connectPeripheraloptions(item, null);
break;
}
}
}
}

//第五步:连接成功,扫描蓝牙设备的服务
function centralManagerdidConnectPeripheral(central, peripheral) {
peripheral.discoverServices(null);
}

//第六步:扫描到外设的所有服务后,筛选指定的服务,扫描该服务的特性
function peripheraldidDiscoverServices(peripheral, error) {
var serUID = CBUUID.UUIDWithString("");
var *services=peripheral.services();
var len = services.count();
for (var i = 0; i < len; i++) {
var item = services.objectAtIndex(i);
if ( item.UUID() === serUID ) {
peripheral.discoverCharacteristicsforService(null, item);
break;
}
}
}

//第七步:扫描到指定服务的特性后,筛选指定的特性,进行交互
function peripheraldidDiscoverCharacteristicsForServiceerror(peripheral, service, error) {
var *characteristics = peripheral.characteristics();
var serUID = CBUUID.UUIDWithString("");
var len = characteristics.count();
for (var i = 0; i < len; i++) {
var characteristic = characteristics.objectAtIndex(i);
if ( characteristic.UUID() === serUID ) {
var data = null;
peripheral.writeValueforCharacteristictype(data,characteristic,0);
}
}
}

function peripheraldidWriteValueForCharacteristiccharacteristicerror(peripheral, characteristic, error) {
output(">>7. 打印完成 <br>");
}

function centralManagerdidDisconnectPeripheralperipheralerror(central, peripheral, error) {
output(">>已断开连接 <br>");
}

function output(msg) {
document.getElementById('result').innerHTML += msg + '<br>';
}

function clearResult() {
document.getElementById('result').innerHTML = '';
}
</script>
</head>

<body>
<div class="mui-content-padded">
<input type="button" class="mui-btn" value="创建管理器" onclick="create()" />
<input type="button" class="mui-btn" value="扫描外设" onclick="scan()" />
<input type="button" class="mui-btn" value="清空输出内容" onclick="clearResult()" />
<div id='result'></div>

</div>
</body>

</html>
\n

实现代理,并调用代理方法发现了蓝牙设备,但获取到的 设备对象peripheral 返回 undefined,求大牛帮忙????


0

JonasLin

赞同来自:

应该是要使用plusGetAttribute来获取属性吧?


0

JonasLin

赞同来自:

你要把获得的 peripheral, advertisementData, RSSI的类给引入进来啊。


0

493387016@qq.com

赞同来自:

请问您现在是怎么解决的啊???能分享一下吗??


0

my128 - 80

赞同来自:

有这人代码吗js/mui.min.js"


0

蓝牙打印机 - 专业生产开发蓝牙打印机产品,应用在进销存、物流、执法项目案例较多,提供相应的开发支持及DEMO,有需要可联系:QQ:81617129,手机:17701729330

赞同来自:

专业生产开发蓝牙打印机产品,应用在进销存、物流、执法项目案例较多,打印机支持安卓、苹果(IOS)系统蓝牙打印,提供相应的开发支持及DEMO,有需要可联系:QQ:81617129,手机:17701729330


0

244096512@qq.com

赞同来自:

楼主,我这边连接蓝牙的回调不执行,请问要怎么解决呢?


0

419196314@qq.com

赞同来自:

不行 直接就闪退了。。。应该怎么搞啊


0

1054478332@qq.com

赞同来自:

厉害了,这个


要回复问题请先登录注册