我想连接到Internet。如果在5秒后我没有连接(使用可及性),我想流产。这可能吗?
nstimer,带回调1秒和一个计数器。如果5次尝试失败,则5秒已经过去了。
类似:
var timerCounter = 0
var timer : NSTimer?
func shouldAttemptConnection() {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "attemptConnection", userInfo: nil, repeats: true)
self.attemptConnection()
}
func attemptConnection() {
if Reachability.isReachable() {
// Handle success code
} else if ++timerCounter >= 5 {
// Handle timeout code
} else {
// Try again
return
}
self.invalidateTimer()
}
func invalidateTimer() {
timer?.invalidate()
timer = nil
timerCounter = 0
}