Skip to content

Instantly share code, notes, and snippets.

@kvannotten
Created June 23, 2014 02:58
Show Gist options
  • Save kvannotten/57ddd5531c228e7e08c6 to your computer and use it in GitHub Desktop.
Save kvannotten/57ddd5531c228e7e08c6 to your computer and use it in GitHub Desktop.
connecting to sockets in swift
var inputStream : NSInputStream?
var outputStream : NSOutputStream?
func connect() {
var readStream : Unmanaged<CFReadStream>?
var writeStream : Unmanaged<CFWriteStream>?
let host : CFString = NSString(string: self.host)
let port : UInt32 = UInt32(self.port)
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream)
inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
inputStream!.delegate = self
outputStream!.delegate = self
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
}
@joolsx
Copy link

joolsx commented Feb 2, 2015

The method CFStreamCreatePairWithSocketToHost(...) is a creation function with 'create' in its name and follows Apple's Create Rule. It therefore returns a retained value and should be retrieved with stream.takeRetainedValue(), as does this gist 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment