swift为NSStream创建字节缓冲区持有者

时间:2014-08-24 22:05:11

标签: swift

Ray Wenderlich tutorial on sockets中的

为了从Objective-C中的输入流中读取字节,我们做了

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

在Swift中,我尝试了以下内容但没有取得多大成功

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

                }
            }
        }

1 个答案:

答案 0 :(得分:17)

您可以使用Array<UInt8>作为缓冲区并将其原样传递给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:]返回一个数字,表示它读取的字节数(如果它是> = 0)或者是否有错误(如果它是负数)。您应该相应地检查返回值。