Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. let data = dataToWrite.first!
  2. self.outputStream.write(&data, maxLength: data.count)
  3.  
  4. Cannot convert value of type 'Data' to expected argument type 'UInt8'
  5.  
  6. let data = ... // a Data value
  7. let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
  8.  
  9. /// Access the bytes in the data.
  10. ///
  11. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
  12. public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType
  13.  
  14. extension OutputStream {
  15.  
  16. /// Write String to outputStream
  17. ///
  18. /// - parameter string: The string to write.
  19. /// - parameter encoding: The String.Encoding to use when writing the string. This will default to UTF8.
  20. /// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string.
  21. ///
  22. /// - returns: Return total number of bytes written upon success. Return -1 upon failure.
  23.  
  24. func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8, allowLossyConversion: Bool = true) -> Int {
  25. if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
  26. var bytesRemaining = data.count
  27. var totalBytesWritten = 0
  28.  
  29. while bytesRemaining > 0 {
  30. let bytesWritten = data.withUnsafeBytes {
  31. self.write(
  32. $0.advanced(by: totalBytesWritten),
  33. maxLength: bytesRemaining
  34. )
  35. }
  36. if bytesWritten < 0 {
  37. // "Can not OutputStream.write(): (self.streamError?.localizedDescription)"
  38. return -1
  39. } else if bytesWritten == 0 {
  40. // "OutputStream.write() returned 0"
  41. return totalBytesWritten
  42. }
  43.  
  44. bytesRemaining -= bytesWritten
  45. totalBytesWritten += bytesWritten
  46. }
  47.  
  48. return totalBytesWritten
  49. }
  50.  
  51. return -1
  52. }
  53. }
  54.  
  55. let data: NSData = dataToWrite.first!
  56. self.outputStream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
  57.  
  58. extension OutputStream {
  59. func write(data: Data) -> Int {
  60. return data.withUnsafeBytes { write($0, maxLength: data.count) }
  61. }
  62. }
  63.  
  64. extension InputStream {
  65. func read(data: inout Data) -> Int {
  66. return data.withUnsafeMutableBytes { read($0, maxLength: data.count) }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement