Fast buffer creation for NSStream

in the Ray Wenderlich tutorial on sockets , to read bytes from the 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)) } } } 
+5
source share
1 answer

You can use Array<UInt8> as a buffer and pass it as 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 reads (if it is> = 0), or if there was an error (if it is negative). You should check the return value accordingly.

+16
source

Source: https://habr.com/ru/post/1201045/


All Articles