Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift create byte buffer holder for NSStream

Tags:

swift

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))

                }
            }
        }
like image 923
Nicolas Manzini Avatar asked Aug 24 '14 22:08

Nicolas Manzini


1 Answers

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.

like image 145
jou Avatar answered Sep 17 '22 19:09

jou