Writing Data to an NSOutputStream in Swift 3

后端 未结 4 927
谎友^
谎友^ 2020-12-14 04:37

The solution of this question no longer works with Swift 3.

There is no longer a property bytes of Data (formerly NSData.

4条回答
  •  轮回少年
    2020-12-14 04:58

    Martin R, thank you for your answer. That was a foundation for a complete solution. Here it is:

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

提交回复
热议问题