Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let data = dataToWrite.first!
- self.outputStream.write(&data, maxLength: data.count)
- Cannot convert value of type 'Data' to expected argument type 'UInt8'
- let data = ... // a Data value
- let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
- /// 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
- 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
- }
- }
- let data: NSData = dataToWrite.first!
- self.outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
- 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) }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement