Guest User

Untitled

a guest
Jul 12th, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 8.57 KB | None | 0 0
  1. import UIKit
  2. import CoreBluetooth
  3. class PrinterVC: UIViewController,UITableViewDataSource,CBCentralManagerDelegate,CBPeripheralDelegate,UITableViewDelegate {
  4.     var writeCharacteristic: CBCharacteristic!
  5.     var selectedUserList = [TransactionDetails]()
  6.     var type : String!
  7.     var name :String!
  8.     lazy var complete : Bool = {
  9.         return false
  10.     }()
  11.     var id : String!
  12.     var manager :CBCentralManager!
  13.     var peripheral : CBPeripheral!
  14.     var peripheralsArray :[CBPeripheral] = []
  15.     var finalPeriPheralArray : [CBPeripheral] = []
  16.     var purchasedCardDetail = [Data1]()
  17.     func centralManagerDidUpdateState(_ central: CBCentralManager) {
  18.         var consolMsg = ""
  19.         switch central.state {
  20.         case .poweredOff: consolMsg = "Bluetooth is off"
  21.         case .poweredOn: consolMsg = "Bluetooth is ON"
  22.         manager.scanForPeripherals(withServices: nil, options: nil)
  23.         case .resetting: consolMsg = "Bluetooth is reset"
  24.         case .unauthorized: consolMsg = "Bluetooth is Unauthorized"
  25.         case .unknown: consolMsg = "Bluetooth is unknown"
  26.         case .unsupported: consolMsg = "Bluetooth is unsupported"
  27.            
  28.         }
  29.         if consolMsg != "Blutooth is ON"{
  30.             popupAlert(title: "", message: consolMsg, actionTitles: ["Ok"], actions:[{ action1 in
  31.                
  32.                
  33.                
  34.                 }])
  35.         }
  36.        
  37.     }
  38.    
  39.     func centralManager(_ central: CBCentralManager,
  40.                         didDisconnectPeripheral peripheral: CBPeripheral,
  41.                         error: Error?)
  42.     {
  43.        
  44.         print("CONNECTION WAS DISCONNECTED is \(String(describing: peripheral.name))")
  45.        
  46.     }
  47.    
  48.     func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
  49.         //        if characteristic.uuid.uuidString == "FF06"{
  50.         //            let value = characteristic.value!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
  51.         //                return pointer.pointee
  52.         //            }
  53.         //            print("value : \(value)")
  54.         //        }
  55.        
  56.         if let error = error {
  57.             print("error : \(error)")
  58.             return
  59.         }
  60.        
  61.         //print("uuid : \(characteristic.uuid)  && value :  \(characteristic.value)")
  62.     }
  63.    
  64.     func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
  65.        
  66.         if let servicePeriPheral = peripheral.services as [CBService]!{
  67.            
  68.             for service in servicePeriPheral{
  69.                 peripheral.discoverCharacteristics(nil, for: service)
  70.                 print("services : \(service.characteristics)")
  71.             }
  72.            
  73.            
  74.         }
  75.     }
  76.    
  77.    
  78.     func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
  79.         if let  CharacterArray = service.characteristics as [CBCharacteristic]!{
  80.            
  81.             for cc in CharacterArray{
  82.                
  83.                 if cc.uuid.uuidString == "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F"{
  84.                     self.writeCharacteristic = cc
  85.                    
  86.                    
  87.                    // print("uuid : \(cc.uuid)  && value :  \(cc.value)")
  88.                     peripheral.readValue(for: cc)
  89.                    
  90.                     print("characteristics : \(cc)")
  91.                 }
  92.             }
  93.         }
  94.     }
  95.    
  96.    
  97.     func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
  98.        
  99.        
  100.        
  101.         if !peripheralsArray.contains(peripheral){
  102.            
  103.             peripheralsArray.append(peripheral)
  104.         }
  105.        
  106.    
  107.         finalPeriPheralArray = [CBPeripheral]()
  108.         for i in 0..<peripheralsArray.count{
  109.             if peripheralsArray[i].name != nil{
  110.                
  111.                 finalPeriPheralArray.append(peripheralsArray[i])
  112.             }
  113.         }
  114.        
  115.         printerTableView.reloadData()
  116.     }
  117.    
  118.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  119.         return finalPeriPheralArray.count
  120.     }
  121.    
  122.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  123.        
  124.         let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PrinterTVC
  125.         let array = finalPeriPheralArray[indexPath.row].name
  126.        
  127.        
  128.         cell.printerNameLabel.text = array
  129.    
  130.         return cell
  131.     }
  132.     func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
  133.         peripheral.delegate = self
  134.         peripheral.discoverServices(nil)
  135.        
  136.         print("did connect : \(peripheral.name!)")
  137.        
  138.         manager.stopScan()
  139.     }
  140.  
  141.    
  142.     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  143.         manager.stopScan()
  144.        
  145.         if let peripheral = finalPeriPheralArray[indexPath.row] as? CBPeripheral{
  146.             print("mydevice:\(peripheral.name)")
  147.            
  148.             self.peripheral = peripheral
  149.             self.peripheral.delegate = self
  150.             self.manager.delegate = self
  151.             print("\(self.peripheral.name!) device is selected")
  152.            
  153.             manager.connect(self.peripheral, options: nil)
  154.    
  155.         }
  156.        
  157.     }
  158.     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  159.         return 40
  160.     }
  161.    
  162.     @IBOutlet weak var printerTableView: UITableView!
  163.     override func viewDidLoad() {
  164.         super.viewDidLoad()
  165.    // print(purchasedCardDetail[0].username)
  166.         manager = CBCentralManager(delegate: self, queue: nil)
  167.         printerTableView.dataSource = self
  168.         printerTableView.delegate = self
  169.         printerTableView.separatorStyle = .none
  170.        
  171.         let rightBarItemButton = UIBarButtonItem(title: "PRINT", style: UIBarButtonItemStyle.plain, target: self, action: #selector(printAction))
  172.         self.navigationItem.rightBarButtonItem = rightBarItemButton
  173.     }
  174.    
  175.     @objc func printAction(){
  176.        
  177.        
  178.        
  179.         let attrs = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)]
  180.         let star = "***********************"
  181.         var escapedString = [String]()
  182.         var originalString  = ""
  183.        
  184.         escapedString.append("\n\(name!)")
  185.         escapedString.append("OP : \(id!)")
  186.         escapedString.append(star)
  187.         let line = "\n------ Thank you --------\n"
  188.        // let wish = "\nThank you"
  189.          if type == "cardPurchase"{
  190.         for i in 0..<purchasedCardDetail.count{
  191.            
  192.             originalString =  "\nUsername : " + " \(purchasedCardDetail[i].username!) " + "\nPassword :  " + " \(purchasedCardDetail[i].password!) "
  193.             let gString = NSMutableAttributedString(string:originalString, attributes:attrs)
  194.             escapedString.append(gString.string)
  195.         }
  196.          }
  197.          else{
  198.             for i in 0..<selectedUserList.count{
  199.                
  200.                 originalString =  "\nUsername : " + " \(selectedUserList[i].username!) " + "\nPassword :  " + " \(selectedUserList[i].password!) "
  201.                 let gString = NSMutableAttributedString(string:originalString, attributes:attrs)
  202.                 escapedString.append(gString.string)
  203.             }
  204.         }
  205.         escapedString.append(line)
  206.        
  207.        
  208.         let  getdata = escapedString.joined(separator: "\n")
  209.        
  210.        
  211.        
  212.  
  213.         var str = getdata
  214.         var byteArray = [UInt8]()
  215.         for char in (str.utf8){
  216.             byteArray += [char]
  217.         }
  218.        //let sizeData = Data(bytes: sizeByteArray)
  219.         let sentData = Data(bytes: byteArray)
  220.         if self.writeCharacteristic != nil
  221.         {
  222.             print("Sent")
  223.            
  224.          
  225.            
  226.                peripheral.writeValue(sentData,  for: writeCharacteristic, type: CBCharacteristicWriteType.withResponse)
  227.            
  228.            
  229.            
  230.            
  231.             let sb = UIStoryboard(name: "Main", bundle: nil)
  232.             let vc = sb.instantiateViewController(withIdentifier: "homeTabbar")
  233.             self.present(vc, animated: true, completion: nil)
  234.         }else
  235.         {
  236.             popupAlert(title: "Couldn't send", message: "select device or Please turn off and turn on again", actionTitles: ["Ok"], actions:[{ action1 in
  237.                
  238.                
  239.                
  240.                 }])
  241.         }
  242.     }
  243. }
Add Comment
Please, Sign In to add comment