Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift, objective-c protocol implementation

Still trying to get used to swift, but since my obj-c knowledge is close to 0, I have not been able to implement this SocketRocket protocol. Any help would be greatly appreciated

Here's the obj-c delegate I try to implement

@protocol SRWebSocketDelegate <NSObject>

// message will either be an NSString if the server is using text
// or NSData if the server is using binary.
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;

@optional

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;

@end

I hoped this was the proper way to implement it; it wasn't...
I get 'SocketDelegate' does not conform to protocol 'SRWebSocketDelegate'

class SocketDelegate:UIViewController, SRWebSocketDelegate{
    let socket:SRWebSocket! = SRWebSocket()

    override func loadView() {
        self.socket.delegate = self
    }    

    func didReceiveMessage(message:AnyObject){

    }
}
like image 680
August Bjornberg Avatar asked Jul 31 '14 09:07

August Bjornberg


2 Answers

The answer is:

func webSocket(webSocket: SRWebSocket!, didReceiveMessage message: AnyObject!)

see

Functions in Swift Reference Book

Method name in Obj-C webSocket:didReceiveMessage is translated such as the first part is the method name, the other parts are the external parameter names (didReceiveMessage). Also note that id becomes AnyObject and Obj-C references are translated with ! as implicitly unwrapped optionals (this is no longer true, implicitly unwrapped optionals are now rare thanks to attributes added to Obj-C declarations).

like image 115
Sulthan Avatar answered Oct 04 '22 04:10

Sulthan


An alternative solution: try Starscream - a native Swift Websocket library.

like image 42
Atorian Avatar answered Oct 04 '22 05:10

Atorian