跳转到内容

Swift SDK

Swift SDK 适用于 iOS 和 macOS 现代应用开发,通过 BLE(低功耗蓝牙)连接打印机设备。

从 GitHub 下载 Framework:Package Center

必须导入:

  • adapter.framework - 设备适配器
  • father.framework - 核心框架

按需导入:

  • cpcl.framework - CPCL 指令
  • esc.framework - ESC 指令
  • tspl.framework - TSPL 指令

创建 YourProject-Bridging-Header.h

#import <adapter/adapter.h>
#import <father/father.h>
#import <tspl/tspl.h>
#import <cpcl/cpcl.h>
#import <esc/esc.h>

在 Build Settings 中设置 Objective-C Bridging Header 路径。

import Foundation
import CoreBluetooth
class PrinterManager: NSObject {
private var lifecycle: Lifecycle?
private var connectedPeripheral: CBPeripheral?
func connect(device: CBPeripheral) {
lifecycle = Lifecycle()
lifecycle?.connectedDevice(device)
connectedPeripheral = device
}
func disconnect() {
connectedPeripheral = nil
lifecycle = nil
}
}

ESC 指令广泛用于热敏小票打印机。详细指令说明请参考 ESC 指令文档

private var escCommand: AYEscCommand?
func setupESC() {
escCommand = AYEscCommand()
}
func printReceipt() {
guard let esc = escCommand else { return }
// 1. 唤醒打印机
esc.wake()
// 2. 使能打印机
esc.enable()
// 3. 打印图片
if let image = UIImage(named: "receipt") {
esc.image(image, compress: false, mode: .normal)
}
// 4. 打印定位(连续纸不需要)
esc.position()
// 5. 结束打印任务
esc.stopPrintJob()
// 6. 发送指令
bleHelper?.writeCommands(esc.commands)
}
// 唤醒打印机
esc.wake()
// 使能打印机
esc.enable()
// 打印图片
esc.image(image, compress: false, mode: .normal)
// 打印定位
esc.position()
// 结束打印任务
esc.stopPrintJob()
// 设置关机时间(单位:分钟,0 表示不关机)
esc.shutTime(10)
// 设置浓度
esc.thickness(.medium) // .low, .medium, .high
// 设置纸张类型
esc.paperType(.continuous) // .blackMark, .continuous, .gap, .hole
// 查询打印机信息
esc.printerInfo()
// 查询打印机状态
esc.state()
// 查询电量
esc.batteryVol()
// 查询蓝牙名称
esc.btName()
// 查询固件版本
esc.printerVersion()
// 查询 MAC 地址
esc.mac()
// 查询 SN 号
esc.sn()
// 查询打印机型号
esc.printerModel()
// 发送指令
bleHelper?.writeCommands(esc.commands)
// 设置回调处理打印机返回数据
escCommand?.read = { [weak self] data, error in
if let data = data {
print("打印机回传: \(data)")
// 解析查询结果或状态信息
}
}

TSPL 指令用于标签条码打印机。详细指令说明请参考 TSPL 指令文档

private var tspl: BasicTSPL?
func setupTSPL() {
tspl = BasicTSPL()
tspl?.basicTSPL(lifecycle, TSPLPrinter_GENERIC)
// 设置回调
tspl?.read = { [weak self] data, error in
if let data = data {
print("打印机回传: \(data)")
}
}
tspl?.bleDidConnectPeripheral = { peripheral in
print("连接成功: \(peripheral.name ?? "")")
}
tspl?.bleDidDisconnectPeripheral = { peripheral, error in
print("连接断开: \(error?.localizedDescription ?? "")")
}
}
func printLabel() {
guard let tspl = tspl else { return }
// 页面设置
let page = TPage().width(60).height(40)
let direction = TDirection().direction(.up_out).mirror(.no_mirror)
// 文字
let title = TText()
.x(180).y(30)
.font(.TSS24)
.xmulti(2).ymulti(2)
.content("商品标签")
// 条码
let barcode = TBarcode()
.x(100).y(200)
.type("128")
.height(60)
.content("6901234567890")
// 二维码
let qrcode = TQRCode()
.x(350).y(100)
.cellWidth(4)
.content("https://example.com")
// 执行打印
tspl.page(page)
.direction(direction)
.gap(true)
.cls()
.text(title)
.barcode(barcode)
.qrcode(qrcode)
.print(1)
}

CPCL 指令用于便携式标签打印机。详细指令说明请参考 CPCL 指令文档

private var cpcl: BasicCPCL?
func setupCPCL() {
cpcl = BasicCPCL()
cpcl?.basicCPCL(lifecycle)
}
func printCPCLLabel() {
guard let cpcl = cpcl else { return }
// 页面设置
let page = CPCLPage().width(576).height(400)
// 文字
let title = CPCLText()
.x(50).y(50)
.content("商品标签")
// 条码
let barcode = CPCLBarcode()
.x(50).y(150)
.content("1234567890")
// 执行打印
cpcl.page(page)
.text(title)
.barcode(barcode)
.print()
}
import CoreBluetooth
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private var centralManager: CBCentralManager!
private var discoveredPeripherals: [CBPeripheral] = []
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func startScan() {
if centralManager.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
}
func stopScan() {
centralManager.stopScan()
}
func connect(_ peripheral: CBPeripheral) {
centralManager.connect(peripheral, options: nil)
}
// MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("蓝牙已开启")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
advertisementData: [String: Any], rssi RSSI: NSNumber) {
if !discoveredPeripherals.contains(peripheral) {
discoveredPeripherals.append(peripheral)
print("发现设备: \(peripheral.name ?? "Unknown")")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("连接成功: \(peripheral.name ?? "")")
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
print("连接断开: \(error?.localizedDescription ?? "")")
}
}

Info.plist 中添加:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>需要蓝牙权限来连接打印机</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>需要蓝牙权限来连接打印机</string>
  • 原生 Swift Package
  • 完整的 Swift API
  • async/await 支持
  • SwiftUI 集成示例
  • Combine 支持
  • macOS 支持优化

完整示例请参考:

关注我们的 GitHub 获取最新进展。

如果你对 Swift SDK 有任何建议或需求,欢迎提交 Issue。