Delegation of Objective-C protocol to Swift

I am using a UDP listener on iOS using the Swift language.

For this, I pass the CocoaAsyncSocket project .

I managed to import the CocoaAsyncSocket library using Bridging-Header.h, I could call functions from Objective-C classes, but I cannot write a delegate function in swift.

This is the code in which I install Socket and define ViewController.swif as the delegate class for the listener:

func setupSocket() {
    var udpSocket : GCDAsyncUdpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    var error : NSError?
    let port : UInt16 = 12121
    let address : String = "228.5.12.12"
    udpSocket.bindToPort(port, error: &error)
    udpSocket.joinMulticastGroup(address, error: &error)
    udpSocket.enableBroadcast(true, error: &error)
    println("228.5.12.12")
}

This is the first delegate function in Objective-C:

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
                                               fromAddress:(NSData *)address
                                         withFilterContext:(id)filterContext;

And finally, this is how I implement the function in Swift:

override func udpSocket(sock : GCDAsyncUdpSocket!, didReceiveData data : NSData!,  fromAddress address : NSData!,  withFilterContext filterContext : AnyObject!) {
    println(data)
}

The ViewController class is declared to implement the correct protocol:

class ViewController: UIViewController, GCDAsyncUdpSocketDelegate {
    ...
}

I have no compilation except overriding.

Question: What am I doing wrong?

+4
2

override . - , override .

+3

, .

1) , udpSocket

2) ARC, , , GCDAsyncUdpSocket, , .

setupSocket, , 0. .

override, .

var udpSocket: GCDAsyncUdpSocket!

func setupSocket() 
{
    udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())

    if (udpSocket == nil)
    {
       // Should display an error here
       return
    }

    // Set delegate 
    udpSocket.delegate = self
    // Other code that you had
}
+1

Source: https://habr.com/ru/post/1548074/


All Articles