2013-06-26 75 views
0

目前,我有我的appdelegate.mSocketRocket調用一個打開的連接

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

一個socketrocket連接,並於

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

我如何可以請求部分從另一種觀點的響應。我似乎無法找到一個委託函數來打開套接字火箭上的當前連接。我似乎無法找到委託函數的邏輯。

回答

1

如果您_webSocket伊娃是由可作爲您AppDelegate的(希望只讀)屬性,從你的代碼的其他地方,你可以檢查的套接字的狀態:

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

不同的狀態列舉here。更好的辦法是將這種支票封裝到- (BOOL)socketIsOpen- (BOOL)socketIsClosed的方法中,在您的AppDelegate中。此外,如果您希望套接字打開以觸發應用程序的其他操作,您可能需要使用諸如NSNotificationCenter之類的東西,以便可以在套接字打開時以及關閉套接字時通知應用程序的任何組件:

- (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) 
    }]; 
} 

這將使您的應用程序的其他部分做:

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

其中socketDidOpen:將採取單一NSNotification*說法。

作爲一般建議,不要等到websocket連接在打開UIWindow鍵之前打開並顯示,否則,如果沒有可用的連接,您的用戶將無法使用您的應用程序。在一般情況下,連接設置應該在後臺進行管理,並在設置應用程序UI時進行異步處理。

+0

你先生,做了這份工作!我總是試圖避免通知中心。不知何故,這似乎不是一個固定的解決方案。但它現在有這個伎倆。謝了哥們。 –

+1

在某些情況下,我還嘗試通過直接構建註冊觀察員並通知他們的方法來避免NSNotificationCenter,但是您需要維護一個觀察者列表,觀察保留週期和線程安全性。在大多數情況下,這是過度殺傷:) – matehat

相關問題