From b7d13e9e013c3b4dc4cfb1734136be8ba409f2aa Mon Sep 17 00:00:00 2001 From: Vasilis Akoinoglou Date: Thu, 27 Sep 2018 17:50:52 +0300 Subject: [PATCH] Fixed an issue with the networking activity indicator where it was always showing (for runningRequests == -1). Refactored the class a bit. --- ws/WSNetworkIndicator.swift | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/ws/WSNetworkIndicator.swift b/ws/WSNetworkIndicator.swift index 2ee8848..eca73b8 100644 --- a/ws/WSNetworkIndicator.swift +++ b/ws/WSNetworkIndicator.swift @@ -15,29 +15,28 @@ import Foundation occur in order to avoid flickering. */ -class WSNetworkIndicator: NSObject { - +class WSNetworkIndicator { + static let shared = WSNetworkIndicator() private var runningRequests = 0 func startRequest() { runningRequests += 1 - // For some unowned reason using scheduledTimer does not work in this case. - let timer = Timer(timeInterval: 1, target: self, selector: #selector(tick), userInfo: nil, repeats: false) - RunLoop.main.add(timer, forMode: RunLoop.Mode.common) + DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in + self?.tick() + } } - + func stopRequest() { runningRequests -= 1 - // For some unowned reason using scheduledTimer does not work in this case. - let timer = Timer(timeInterval: 0.2, target: self, selector: #selector(tick), userInfo: nil, repeats: false) - RunLoop.main.add(timer, forMode: RunLoop.Mode.common) + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) { [weak self] in + self?.tick() + } } - - @objc + func tick() { let previousValue = UIApplication.shared.isNetworkActivityIndicatorVisible - let newValue = (runningRequests != 0) + let newValue = (runningRequests > 0) if newValue != previousValue { UIApplication.shared.isNetworkActivityIndicatorVisible = newValue }