简体   繁体   中英

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){

    }
}

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).

另一种解决方案:尝试Starscream - 一个原生的Swift Websocket库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM