如果您_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時進行異步處理。
你先生,做了這份工作!我總是試圖避免通知中心。不知何故,這似乎不是一個固定的解決方案。但它現在有這個伎倆。謝了哥們。 –
在某些情況下,我還嘗試通過直接構建註冊觀察員並通知他們的方法來避免NSNotificationCenter,但是您需要維護一個觀察者列表,觀察保留週期和線程安全性。在大多數情況下,這是過度殺傷:) – matehat