1

I have a custom ViewController delegate class, which handles ui actions such as button clicked and display text in a text view.

Now I want to use AsyncSocket in the class. I have been able to create a socket object

var tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())

Now I want to implement those callback functions, such as didConnectToHosts(...) whose declaration is provided in GCDAsyncSocket.h:

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;

How do I implement this function in my swift class?

user3739779
  • 183
  • 2
  • 6

1 Answers1

6
// - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16) 

// - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;      
func socket(socket : GCDAsyncSocket, didReadData data:NSData, withTag tag:Int32) 

Don't forget to make your swift class inherit from NSObject, otherwise the GCDAsyncSocket will fail to assign it as a delegate.

Also, do not mark any parameters as var as in var didReadData data:NSData

Anton
  • 1,655
  • 15
  • 16
  • One newbie question. Why my class doesn't have to inherit GCDAsyncSocketDelegate defined in GCDAsyncSocket.h to receive callbacks? – user3739779 Jun 15 '14 at 02:30
  • Probably because the GCDAsyncSocket class specifies `delegate` as plain `id` without the protocol. For example, look at the `setDelegate:(id)value` Swift translates `id` into `AnyObject?` and the call into `setDelegate(value:AnyObject?)`. If the GCDAsyncSocket developer had specified the protocol: `setDelegate:(id)value`, the Swift would be `setDelegate(value:GCDAsyncSocketDelegate?)` and you'd have to subclass GCDAsyncSocketDelegate in your class. – Anton Jun 15 '14 at 03:04
  • Is there possibly an issue with this in Swift 3? I am running into the issue where didConnectToHost doesn't get called. I looked at [this](http://stackoverflow.com/questions/35805299/gcdasyncsocket-in-swift) thread as well and while no error is getting thrown, the callback is not getting called. – Eden May 16 '17 at 08:14
  • @Anton Could you please give a complete minimal example? – PascalS Apr 10 '18 at 10:02