如果你想在没有得到回复时显示一些消息,你可以使用 a Timer
,它看起来像这样的基础:
var timer: Timer?
var responseTimeout: TimeInterval = 15
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: responseTimeout, repeats: false, block: {[weak self] timer in
self?.onResponseTimeout()
})
}
func onResponseTimeout() {
print("Didn't get response")
}
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
print(message)
timer?.invalidate() //invalidate timer when you get a message
}
然后您可以startTimer()
在需要时调用,即打开套接字时:
func webSocketDidOpen(_ webSocket: SRWebSocket!) {
print("webSocketDidOpen")
showTableView()
startTimer()
}
或在您发送消息后:
socketRocket?.send(message)
startTimer()
如果您还想为连接设置超时(它与 resopone timout 不同),您可以使用URLRequest
代替URL
:
let request = URLRequest(url: url, timeoutInterval: 30) //it is 30 sec connection timeout
socketRocket = SRWebSocket(urlRequest: request)
socketRocket?.delegate = self
socketRocket?.open()
支持连接和响应超时的完整类:
import Foundation
import SocketRocket
class WebSocket: NSObject, SRWebSocketDelegate {
var socketRocket: SRWebSocket?
var timer: Timer?
var responseTimeout: TimeInterval = 15
func open(url: URL, connectionTimeout: TimeInterval = 10) {
let request = URLRequest(url: url, timeoutInterval: connectionTimeout)
socketRocket = SRWebSocket(urlRequest: request)
socketRocket?.delegate = self
socketRocket?.open()
}
func send(message: String) {
socketRocket?.send(message)
startTimer()
}
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: responseTimeout, repeats: false, block: {[weak self] timer in
self?.onResponseTimeout()
})
}
func onResponseTimeout() {
print("Didn't get response")
}
func webSocketDidOpen(_ webSocket: SRWebSocket!) {
print("webSocketDidOpen")
startTimer()
}
func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
print("closed with code: \(code), reason: \(reason), wasClean: \(wasClean)")
timer?.invalidate()
}
func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
print("didFailWithError\(error)")
timer?.invalidate()
}
func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
print(message)
timer?.invalidate()
}
}