Socket Client (Unexpectedly found nil while implicitly unwrapping an optional value)

Hey I've written a socket client and have the following problem, when I send a message to my socket server for the first time, it comes on and everything works, but if I send another message (the second message) (for example, the same one ) comes the error [Fatal error: Unexpectedly found nil while implicitly unwrapping an optional value]. I hope someone can help me with this problem.😕


func sendData(data: AnyObject) {
        
        let sendData = "\(data)\r\n"
        guard let sendDataUFT = sendData.data(using: .utf8) else { return }
        let sendDataCount = sendDataUFT.count
        
        let bytesWritten: Int = sendDataUFT.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in
            
            return outputStream.write(buffer, maxLength: sendDataCount) (<-- The mistake comes in this line)
            
        }
        
        if bytesWritten < sendDataCount {
            
            
            
        }
        
    }

Replies

Probably somewhere else in your code you’ve set outputStream to nil. Or it hasn’t been initialized properly the second time around. I recommend setting some breakpoints and stepping through your code in the debugger to understand the sequence of events.