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.
From this Objective-C-based question I found that it could be done like this in Objective-C:
#include <sys/socket.h>
...
CFDataRef socketData = CFReadStreamCopyProperty((__bridge CFReadStreamRef)(stream), kCFStreamPropertySocketNativeHandle);
CFSocketNativeHandle socket;
CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&socket);
CFRelease(socketData);
int on = 1;
if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) {
NSLog(@"setsockopt failed: %s", strerror(errno));
}
My current Swift implementation/translation looks like this:
var socketData = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySocketNativeHandle) as CFDataRef
var socket: CFSocketNativeHandle
CFDataGetBytes(socketData, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8).self&socket)
var on: UInt8 = 1;
if setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &on, 255) == -1 {
}
A few notes:
inputStream
is declared as:var inputStream: NSInputStream?
- I'm not sure if using
255
as an alternative tosizeof(on)
is a good idea. - The code happens in the function
func stream(theStream:NSStream, handleEvent streamEvent:NSStreamEvent)
which is required by using theNSStreamDelegate
protocol. - I'm not sure if using
inputStream
instead oftheStream
(function parameter) is a good idea.
I'm getting an Xcode error on the CFDataGetBytes
function. It says the following:
'NSData' is not a subtype of of 'CFData'
Any idea how to fix that?
Also, how do I import/include <sys/socket.h>
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?