我正在尝试将数据发送到 OutputStream 以与另一个设备进行通信。 (为此,我使用外部附件框架)但该功能不起作用。我遇到错误无法找到成员“write”。我希望有人可以帮助我找到解决方案。谢谢。
func _writeData() {
while (_session.outputStream.hasSpaceAvailable && _write.length > 0) {
var bytesWritten: Int = _session?.outputStream.write(_write.bytes, _write.length);
if(bytesWritten == -1){
println("write error");
break;
}
else if (bytesWritten > 0){
_write.replaceBytesInRange(NSMakeRange(0, bytesWritten), withBytes: nil, length: 0);
}
}
}
//high level write data method
func writeData(data: NSData) {
if(_write == nil) {
_write = NSMutableData.alloc();
}
_write.appendData(data);
self._writeData();
}
错误--------> var bytesWritten: Int = _session?.outputStream.write(_write.bytes, _write.length);
有我打开和关闭 session 的功能
//使用附件打开 session 并在默认运行循环上设置输入和输出流 func openSession(附件: EAAccessory, withProtocolString protocolString: String) -> ObjCBool{
_session = EASession(accessory: accessory, forProtocol: protocolString);
if(_session != nil) {
_session.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode);
_session.inputStream.open()
_session.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode);
_session.outputStream.open();
} else {
println("Creating session failed");
}
return (_session != nil);
}
//close the session with the accessory
func closeSession() {
_session.inputStream.close();
_session.inputStream.removeFromRunLoop(NSRunLoop(), forMode: NSDefaultRunLoopMode);
_session.outputStream.close();
_session.outputStream.removeFromRunLoop(NSRunLoop(), forMode: NSDefaultRunLoopMode);
}
最佳答案
经过很多测试后,我已经能够写入套接字,这是我的代码:
var inputStream: NSInputStream?
var outputStream: NSOutputStream?
NSStream.getStreamsToHostWithName("localhost", port: 8443, inputStream: &inputStream, outputStream: &outputStream)
outputStream?.open()
inputStream?.open()
//while(true){
//get input
//}
let data: NSData = "this is a test string".dataUsingEncoding(NSUTF8StringEncoding)!
outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
您可以使用net cat进行测试
nc -l 8443
关于ios - swift OutputStream 找不到成员 "write",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24881065/