in the Ray Wenderlich tutorial on sockets in order to read bytes from an input stream in Objective-C we did
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
}
In Swift i tried the following without much success
if (stream == inputStream) {
// var buffer = Array<UInt8>(count: 1024, repeatedValue: 0)
var buffer : UnsafeMutablePointer<UInt8>
var len : Bool
while (inputStream?.hasBytesAvailable == true) {
len = inputStream?.getBuffer(buffer, length: sizeofValue(buffer))
if (len) {
var output = String(NSString(bytes: buffer, length: sizeofValue(buffer), encoding: NSASCIIStringEncoding))
}
}
}
You can use a use an Array<UInt8>
as the buffer and pass it as it is documented in Using Swift with Cocoa and Objective-C:
let bufferSize = 1024
var buffer = Array<UInt8>(count: bufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: bufferSize)
if bytesRead >= 0 {
var output = NSString(bytes: &buffer, length: bytesRead, encoding: NSUTF8StringEncoding)
} else {
// Handle error
}
-[NSInputStream read:maxLength:]
returns a number indicating how many bytes it read (if it's >= 0) or if there was an error (if it's negative). You should check the return value accordingly.
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