将数据写入Swift 3中的NSOutputStream

ahy*_*dev 10 foundation nsdata nsoutputstream swift swift3

这个问题的解决方案不再适用于Swift 3.

不再有一个属性bytesData(前身NSData.

let data = dataToWrite.first!
self.outputStream.write(&data, maxLength: data.count)
Run Code Online (Sandbox Code Playgroud)

使用此代码,我收到错误:

Cannot convert value of type 'Data' to expected argument type 'UInt8'
Run Code Online (Sandbox Code Playgroud)

你怎么能写DataNSOutputStream斯威夫特3?

Mar*_*n R 13

NSData有一个bytes属性来访问字节.DataSwift 3中的新值类型有一个withUnsafeBytes() 方法,它调用一个带有指向字节的指针的闭包.

所以这就是你写Data一个NSOutputStream (没有强制转换NSData)的方式:

let data = ... // a Data value
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
Run Code Online (Sandbox Code Playgroud)

备注: withUnsafeBytes()是一种通用方法:

/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType
Run Code Online (Sandbox Code Playgroud)

在上面的调用中,编译器(as 和)自动推断出这两个ContentType并且不需要额外的 转换.ResultTypeUInt8IntUnsafePointer()

outputStream.write()返回实际写入的字节数.通常,您应该检查该值.可能是-1写入操作失败,或者少于data.count写入带有流控制的套接字,管道或其他对象时.


Ser*_*lov 5

马丁·R,谢谢您的回答。这是完整解决方案的基础。这里是:

extension OutputStream {

    /// Write String to outputStream
    ///
    /// - parameter string:                The string to write.
    /// - parameter encoding:              The String.Encoding to use when writing the string. This will default to UTF8.
    /// - parameter allowLossyConversion:  Whether to permit lossy conversion when writing the string.
    ///
    /// - returns:                         Return total number of bytes written upon success. Return -1 upon failure.

    func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8, allowLossyConversion: Bool = true) -> Int {
        if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
            var bytesRemaining = data.count
            var totalBytesWritten = 0

            while bytesRemaining > 0 {
                let bytesWritten = data.withUnsafeBytes {
                    self.write(
                        $0.advanced(by: totalBytesWritten),
                        maxLength: bytesRemaining
                    )
                }
                if bytesWritten < 0 {
                    // "Can not OutputStream.write(): \(self.streamError?.localizedDescription)"
                    return -1
                } else if bytesWritten == 0 {
                    // "OutputStream.write() returned 0"
                    return totalBytesWritten
                }

                bytesRemaining -= bytesWritten
                totalBytesWritten += bytesWritten
            }

            return totalBytesWritten
        }

        return -1
    }
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*lov 5

只需使用此扩展名:

迅捷5

extension OutputStream {
  func write(data: Data) -> Int {
    return data.withUnsafeBytes {
      write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

对于InputStream

extension InputStream {
  func read(data: inout Data) -> Int {
    return data.withUnsafeMutableBytes {
      read($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: data.count)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特4

extension OutputStream {
  func write(data: Data) -> Int {
    return data.withUnsafeBytes { write($0, maxLength: data.count) }
  }
}
extension InputStream {
  func read(data: inout Data) -> Int {
    return data.withUnsafeMutableBytes { read($0, maxLength: data.count) }
  }
}
Run Code Online (Sandbox Code Playgroud)