title: Swift: TCP socket keep-alive
body: <p>I'm developing an iOS app (using Swift) which uses a TCP connection to a TCP server. Currently, whenever I've sent something, the connection closes automatically. I want to keep the connection open/alive until I manually close it.</p>
  
  <p>From <a href="https://stackoverflow.com/questions/15785917/nsstream-tcp-keep-alive-ios">this Objective-C-based question</a> I found that it could be done like this in Objective-C:</p>
  
  <pre><code>#include &lt;sys/socket.h&gt;
  ...
  CFDataRef socketData = CFReadStreamCopyProperty((__bridge CFReadStreamRef)(stream), kCFStreamPropertySocketNativeHandle);
  CFSocketNativeHandle socket;
  CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&amp;socket);
  CFRelease(socketData);
  
  int on = 1;
  if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &amp;on, sizeof(on)) == -1) {
      NSLog(@"setsockopt failed: %s", strerror(errno));
  }
  </code></pre>
  
  <p>My current Swift implementation/translation looks like this:</p>
  
  <pre><code>var socketData = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySocketNativeHandle) as CFDataRef
  var socket: CFSocketNativeHandle
  CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8).self&amp;socket)
  
  var on: UInt8 = 1;
  if setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &amp;on, 255) == -1 {
  }
  </code></pre>
  
  <p>A few notes:</p>
  
  <ul>
  <li><code>inputStream</code> is declared as: <code>var inputStream: NSInputStream?</code> </li>
  <li>I'm not sure if using <code>255</code> as an alternative to <code>sizeof(on)</code> is a good idea.</li>
  <li>The code happens in the function <code>func stream(theStream:NSStream, handleEvent streamEvent:NSStreamEvent)</code> which is required by using the <code>NSStreamDelegate</code> protocol.</li>
  <li>I'm not sure if using <code>inputStream</code> instead of <code>theStream</code> (function parameter) is a good idea.</li>
  </ul>
  
  <p>I'm getting an Xcode error on the <code>CFDataGetBytes</code> function. It says the following:</p>
  
  <blockquote>
    <p>'NSData' is not a subtype of of 'CFData'</p>
  </blockquote>
  
  <p>Any idea how to fix that?</p>
  
  <p>Also, how do I import/include <code>&lt;sys/socket.h&gt;</code> in my Swift file? I've seen something called bridging headers, but isn't that only for Obj-C side-by-side with Swift implementations?</p>