huyong1978
huyong1978
  • 发布:2015-11-02 16:59
  • 更新:2018-12-16 01:58
  • 阅读:8452

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

分类:Native.js

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  
2015-11-02 16:59 负责人:无 分享
已邀请:

最佳回复

DCloud_heavensoft

DCloud_heavensoft

huyong1978

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>

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

  • DCloud_IOS_XTY

    目前delegte只支持放回一个参数,多参数支持正在开发中

    2015-11-10 16:15

  • huyong1978 (作者)

    麻烦更新后,再回复一下这个帖子,我到时候整理一份nativejs ios打印的示例代码

    2015-11-13 09:46

  • wujianfeng

    回复 huyong1978:现在IOS连接蓝牙搞定了没?

    2016-03-28 10:13

  • 龙之吻

    回复 huyong1978:这个现在可以用了吗?

    2017-10-16 15:34

  • 1234667777

    这个例子可以用了吗?

    2017-12-11 22:26

  • wnsuan

    回复 DCloud_IOS_XTY:这个例子可以用了吗?

    2018-07-25 11:20

  • typer

    回复 DCloud_IOS_XTY:请问现在delegte能返回多个参数了吗??┐(‘~`;)┌ 

    2018-08-23 18:48

  • 首席劝退师

    回复 DCloud_IOS_XTY:现在多个解决没

    2018-08-27 09:51

JonasLin

JonasLin

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

JonasLin

JonasLin

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

4***@qq.com

4***@qq.com

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

my128

my128 - 80

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

蓝牙打印机

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

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

2***@qq.com

2***@qq.com - 小板栗

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

4***@qq.com

4***@qq.com - 海浪

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

1***@qq.com

1***@qq.com

厉害了,这个

该问题目前已经被锁定, 无法添加新回复