2

I am trying to use GCDAsyncSocket to connect my app.

I get compilation errors. When I try this:

    class Connection : NSObject {    
    var connected: Bool
    var tcpSocket: GCDAsyncSocket?
    var myHost: String = "127.0.0.1"
    var myPort: UInt16 = 0

    init() {
        connected = false
    }
    func initialize(host: String, port: UInt16) {

    }
    func connect() {
        tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
        var error: NSError?
        tcpSocket!.connectToHost(myHost, port: myPort, error: error)

    }
}

I get: "Missing argument for parameter 'withTimeout' in call" when changing to this:

class Connection : NSObject {    
var connected: Bool
var tcpSocket: GCDAsyncSocket?
var myHost: String = "127.0.0.1"
var myPort: UInt16 = 0

init() {
    connected = false
}
func initialize(host: String, port: UInt16) {

}
func connect() {
    tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    var connectionError: NSError?
    tcpSocket!.connectToHost(myHost, port: myPort, withTimeout: -1.0, error: connectionError)

}}

I get: "Extra argument 'withTimeout' in call" I am confused...

1 Answers1

1

The definition of that method is:

- (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;

A closer look at the last parameter errPtr reveals that you have to pass the pointer to a variable of type NSError. That translates in swift as a parameter passed using the inout modifier.

So the correct way to call that method is:

tcpSocket!.connectToHost(myHost, onPort: myPort, error: &error)

Note that there was a mispelled parameter in your code: port: myPort should be onPort: myPort

Antonio
  • 71,651
  • 11
  • 148
  • 165