Reputation: 21
I'm trying for a while to send data to an OutputStream to communicate with another device. (For this i use the External Accessory Framework) But the function does not work. I have the error Could not find member "write". I hope somebody can help me to find the solution. thank you.
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();
}
The Error --------> var bytesWritten: Int = _session?.outputStream.write(_write.bytes, _write.length);
There are the function where i open and close the session
//open a session with the accessory and set up the input and output stream on the default run loop func openSession(accessory: 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);
}
Upvotes: 2
Views: 2477
Reputation: 43
after testing many things, I have been able to write to the socket, here is my code:
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)
you can test it using net cat
nc -l 8443
Upvotes: 2