In Obj-C this code is used to convert an NSData to unsigned char:
unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);
In Swift unsigned char is supposedly called CUnsignedChar, but how do i convert an NSData object to CUnsignedChar in Swift?
This could be what you are looking for:
let commandsToPrint: NSData = ...
// Create char array with the required size:
var dataToSentToPrinter = [CUnsignedChar](count: commandsToPrint.length, repeatedValue: 0)
// Fill with bytes from NSData object:
commandsToPrint.getBytes(&dataToSentToPrinter, length: sizeofValue(dataToSentToPrinter))
Update: Actually you don't need to copy the data at all (neither in the Objective-C code nor in Swift). It is sufficient to have a pointer to the data. So your code could look like this (compare Error ("'()' is not identical to 'UInt8'") writing NSData bytes to NSOutputStream using the write function in Swift for a similar problem):
let dataToSentToPrinter = UnsafePointer<CUnsignedChar>(commandsToPrint.bytes)
let commandSize = commandsToPrint.length
var totalAmountWritten = 0
while totalAmountWritten < commandSize {
let remaining = commandSize - totalAmountWritten
let amountWritten = starPort.writePort(dataToSentToPrinter, totalAmountWritten, remaining)
totalAmountWritten += amountWritten
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With