Receipt printing connection close duration.

I'm currently working on an IOS app written in swift to print receipts using the Zebra ZQ520 printer with linkOS v1.4.948. Previously I was facing a problem that the printer sometimes does not print the receipt. The problem seems to be the connection is closed before all the data is sent. So what I did was setting a sleep duration before closing the connection. However this method does not seem to be reliable. Is there any way to check if all the data is sent to the printer before closing the connection? The following is my code:


func printReceiptLabel(completionHandler: (Bool) -> Void) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

            guard let conn = self.openConnection() else {

                dispatch_async(dispatch_get_main_queue()) {

                    self.displayAlertMessage("No printers found")





            let open =

            let receiptGenerator = ReceiptGenerator()


            if let receiptInfo = self.printReceipt {

                let receiptString = receiptGenerator.createReceiptString(receiptInfo)

                let receiptData = receiptString.dataUsingEncoding(NSUTF8StringEncoding) as! NSMutableData


                if open {

                    let blockSize = 1024

                    let totalSize = receiptData.length

                    var bytesRemaining = totalSize

                    var error: NSError?


                    while bytesRemaining > 0 {

                        print("Bytes sent")

                        let bytesToSend = min(blockSize, bytesRemaining)

                        let range = NSMakeRange(0, bytesToSend)



                        let partialLabel = receiptData.subdataWithRange(range)

                        conn.write(partialLabel, error: &error)


                        bytesRemaining -= bytesToSend


                        receiptData.replaceBytesInRange(range, withBytes: nil, length: 0)





                    dispatch_async(dispatch_get_main_queue(), { () -> Void in



                } else {

                    dispatch_async(dispatch_get_main_queue()) {


                        self.displayAlertMessage("Error connecting to printer")