Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import CoreBluetooth
- class PrinterVC: UIViewController,UITableViewDataSource,CBCentralManagerDelegate,CBPeripheralDelegate,UITableViewDelegate {
- var writeCharacteristic: CBCharacteristic!
- var selectedUserList = [TransactionDetails]()
- var type : String!
- var name :String!
- lazy var complete : Bool = {
- return false
- }()
- var id : String!
- var manager :CBCentralManager!
- var peripheral : CBPeripheral!
- var peripheralsArray :[CBPeripheral] = []
- var finalPeriPheralArray : [CBPeripheral] = []
- var purchasedCardDetail = [Data1]()
- func centralManagerDidUpdateState(_ central: CBCentralManager) {
- var consolMsg = ""
- switch central.state {
- case .poweredOff: consolMsg = "Bluetooth is off"
- case .poweredOn: consolMsg = "Bluetooth is ON"
- manager.scanForPeripherals(withServices: nil, options: nil)
- case .resetting: consolMsg = "Bluetooth is reset"
- case .unauthorized: consolMsg = "Bluetooth is Unauthorized"
- case .unknown: consolMsg = "Bluetooth is unknown"
- case .unsupported: consolMsg = "Bluetooth is unsupported"
- }
- if consolMsg != "Blutooth is ON"{
- popupAlert(title: "", message: consolMsg, actionTitles: ["Ok"], actions:[{ action1 in
- }])
- }
- }
- func centralManager(_ central: CBCentralManager,
- didDisconnectPeripheral peripheral: CBPeripheral,
- error: Error?)
- {
- print("CONNECTION WAS DISCONNECTED is \(String(describing: peripheral.name))")
- }
- func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
- // if characteristic.uuid.uuidString == "FF06"{
- // let value = characteristic.value!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
- // return pointer.pointee
- // }
- // print("value : \(value)")
- // }
- if let error = error {
- print("error : \(error)")
- return
- }
- //print("uuid : \(characteristic.uuid) && value : \(characteristic.value)")
- }
- func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
- if let servicePeriPheral = peripheral.services as [CBService]!{
- for service in servicePeriPheral{
- peripheral.discoverCharacteristics(nil, for: service)
- print("services : \(service.characteristics)")
- }
- }
- }
- func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
- if let CharacterArray = service.characteristics as [CBCharacteristic]!{
- for cc in CharacterArray{
- if cc.uuid.uuidString == "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F"{
- self.writeCharacteristic = cc
- // print("uuid : \(cc.uuid) && value : \(cc.value)")
- peripheral.readValue(for: cc)
- print("characteristics : \(cc)")
- }
- }
- }
- }
- func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
- if !peripheralsArray.contains(peripheral){
- peripheralsArray.append(peripheral)
- }
- finalPeriPheralArray = [CBPeripheral]()
- for i in 0..<peripheralsArray.count{
- if peripheralsArray[i].name != nil{
- finalPeriPheralArray.append(peripheralsArray[i])
- }
- }
- printerTableView.reloadData()
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return finalPeriPheralArray.count
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PrinterTVC
- let array = finalPeriPheralArray[indexPath.row].name
- cell.printerNameLabel.text = array
- return cell
- }
- func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
- peripheral.delegate = self
- peripheral.discoverServices(nil)
- print("did connect : \(peripheral.name!)")
- manager.stopScan()
- }
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- manager.stopScan()
- if let peripheral = finalPeriPheralArray[indexPath.row] as? CBPeripheral{
- print("mydevice:\(peripheral.name)")
- self.peripheral = peripheral
- self.peripheral.delegate = self
- self.manager.delegate = self
- print("\(self.peripheral.name!) device is selected")
- manager.connect(self.peripheral, options: nil)
- }
- }
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- return 40
- }
- @IBOutlet weak var printerTableView: UITableView!
- override func viewDidLoad() {
- super.viewDidLoad()
- // print(purchasedCardDetail[0].username)
- manager = CBCentralManager(delegate: self, queue: nil)
- printerTableView.dataSource = self
- printerTableView.delegate = self
- printerTableView.separatorStyle = .none
- let rightBarItemButton = UIBarButtonItem(title: "PRINT", style: UIBarButtonItemStyle.plain, target: self, action: #selector(printAction))
- self.navigationItem.rightBarButtonItem = rightBarItemButton
- }
- @objc func printAction(){
- let attrs = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)]
- let star = "***********************"
- var escapedString = [String]()
- var originalString = ""
- escapedString.append("\n\(name!)")
- escapedString.append("OP : \(id!)")
- escapedString.append(star)
- let line = "\n------ Thank you --------\n"
- // let wish = "\nThank you"
- if type == "cardPurchase"{
- for i in 0..<purchasedCardDetail.count{
- originalString = "\nUsername : " + " \(purchasedCardDetail[i].username!) " + "\nPassword : " + " \(purchasedCardDetail[i].password!) "
- let gString = NSMutableAttributedString(string:originalString, attributes:attrs)
- escapedString.append(gString.string)
- }
- }
- else{
- for i in 0..<selectedUserList.count{
- originalString = "\nUsername : " + " \(selectedUserList[i].username!) " + "\nPassword : " + " \(selectedUserList[i].password!) "
- let gString = NSMutableAttributedString(string:originalString, attributes:attrs)
- escapedString.append(gString.string)
- }
- }
- escapedString.append(line)
- let getdata = escapedString.joined(separator: "\n")
- var str = getdata
- var byteArray = [UInt8]()
- for char in (str.utf8){
- byteArray += [char]
- }
- //let sizeData = Data(bytes: sizeByteArray)
- let sentData = Data(bytes: byteArray)
- if self.writeCharacteristic != nil
- {
- print("Sent")
- peripheral.writeValue(sentData, for: writeCharacteristic, type: CBCharacteristicWriteType.withResponse)
- let sb = UIStoryboard(name: "Main", bundle: nil)
- let vc = sb.instantiateViewController(withIdentifier: "homeTabbar")
- self.present(vc, animated: true, completion: nil)
- }else
- {
- popupAlert(title: "Couldn't send", message: "select device or Please turn off and turn on again", actionTitles: ["Ok"], actions:[{ action1 in
- }])
- }
- }
- }
Add Comment
Please, Sign In to add comment