Question

i currently have a socketrocket connection in my appdelegate.m

_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://pinkfalcon.nl:12345/connectr"]]];
_webSocket.delegate = self;
[_webSocket open];

And the response to that

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    [self.window makeKeyAndVisible];
    NSLog(@"Websocket Connected");
}

How can i request that part from another view. I can't seem to find a delegate function to open a current connection on socket rocket. I can't seem to find the logic of the delegate function.

Was it helpful?

Solution

If your _webSocket ivar is made available as a (hopefully readonly) property of your AppDelegate, from elsewhere in your code you can check the socket's state as :

if ([UIApplication sharedApplication].delegate.webSocket.readyState == SR_OPEN) {}

The different states are enumerated here. Better yet would be to encapsulate this sort of checks into methods like - (BOOL)socketIsOpen or - (BOOL)socketIsClosed in your AppDelegate.

Also, if you want the socket opening to trigger other actions of your applications, you might want to use something like NSNotificationCenter, so any parts of your app can be notified of when the socket is open, and when it is closed:

- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    // your existing code
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"myapp.websocket.open" object:webSocket];
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code
           reason:(NSString *)reason
         wasClean:(BOOL)wasClean; {

    // your code
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"myapp.websocket.close" 
                          object:webSocket
                        userInfo:@{
        @"code": @(code), 
        @"reason": reason, 
        @"clean": @(wasClean)
    }];
}

This would allow other parts of your app to do:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(socketDidOpen:)
                                             name:@"myapp.websocket.open"
                                           object:nil];

where socketDidOpen: would take a single NSNotification* argument.

As a general advice, though, you shouldn't wait for a websocket connection to be open before making your UIWindow key and visible, as that would make your user inapt to use your app if no connection is available. In the general case, connection setup should be managed in the background and be asynchronous with setting up your application UI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top