Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

nsdata - Writing Data to an NSOutputStream in Swift 3

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

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

let data = dataToWrite.first!
self.outputStream.write(&data, maxLength: data.count)

With this code, I get the error:

Cannot convert value of type 'Data' to expected argument type 'UInt8'

How can you write Data to an NSOutputStream in Swift 3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NSData had a bytes property to access the bytes. The new Data value type in Swift 3 has a withUnsafeBytes() method instead, which calls a closure with a pointer to the bytes.

So this is how you write Data to an NSOutputStream (without casting to NSData):

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

Remarks: withUnsafeBytes() is a generic method:

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

In the above call, both ContentType and ResultType are automatically inferred by the compiler (as UInt8 and Int), making additional UnsafePointer() conversions unnecessary.

outputStream.write() returns the number of bytes actually written. Generally, you should check that value. It can be -1 if the write operation failed, or less than data.count when writing to sockets, pipes, or other objects with a flow control.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...