【问题标题】:swift OutputStream could not find member "write"swift OutputStream 找不到成员“写”
【发布时间】:2023-03-14 23:41:02
【问题描述】:

我正在尝试将数据发送到 OutputStream 以与另一台设备通信。 (为此我使用外部附件框架)但该功能不起作用。我有错误找不到成员“写”。我希望有人可以帮助我找到解决方案。谢谢。

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);

有我打开和关闭会话的功能

//打开与附件的会话并在默认运行循环上设置输入和输出流 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);
}

【问题讨论】:

  • 我不会用 '_' 开始你的函数,它在 Swift 中的其他地方使用 - 如果你打算将该函数标记为从 beta 4 开始的私有函数,这可以通过私有函数 yourFunction() 来实现。我也不会把 _ 放在变量名前面;)

标签: ios swift nsstream external-accessory nsoutputstream


【解决方案1】:

在测试了很多东西之后,我已经能够写入套接字,这是我的代码:

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2023-04-08
    相关资源
    最近更新 更多