Skip to content

Commit

Permalink
Stop/restart timer when the app goes to background or enter foreground
Browse files Browse the repository at this point in the history
  • Loading branch information
leandroalonso committed Nov 5, 2020
1 parent 0015fc9 commit 629db96
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
29 changes: 26 additions & 3 deletions WordPress/Classes/Utility/ABTesting/ExPlat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ class ExPlat: ABTesting {
return ttlDate.timeIntervalSinceReferenceDate - Date().timeIntervalSinceReferenceDate
}

private(set) var scheduleTimer: Timer?
private(set) var scheduledTimer: Timer?

init(configuration: ExPlatConfiguration,
service: ExPlatService? = nil) {
self.service = service ?? ExPlatService(configuration: configuration)
subscribeToNotifications()
}

/// Only refresh if the TTL has expired
Expand Down Expand Up @@ -73,15 +74,15 @@ class ExPlat: ABTesting {

private func scheduleRefresh() {
if ttl > 0 {
scheduleTimer?.invalidate()
scheduledTimer?.invalidate()

/// Schedule the refresh on a background thread
DispatchQueue.global(qos: .background).async { [weak self] in
guard let `self` = self else {
return
}

self.scheduleTimer = Timer.scheduledTimer(withTimeInterval: self.ttl, repeats: true) { [weak self] timer in
self.scheduledTimer = Timer.scheduledTimer(withTimeInterval: self.ttl, repeats: true) { [weak self] timer in
self?.refresh()
timer.invalidate()
}
Expand All @@ -94,4 +95,26 @@ class ExPlat: ABTesting {
refresh()
}
}

/// Check if the app is entering background and/or foreground
/// and start/stop the timers
///
private func subscribeToNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}

/// When the app goes to background stop the timer
///
@objc private func applicationDidEnterBackground() {
scheduledTimer?.invalidate()
}

/// When the app enter foreground refresh the assignments or
/// start the timer
///
@objc private func applicationWillEnterForeground() {
refreshIfNeeded()
}
}
4 changes: 2 additions & 2 deletions WordPress/WordPressTest/ABTesting/ExPlatTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ class ExPlatTests: XCTestCase {
abTesting.refresh {

DispatchQueue.main.async {
XCTAssertTrue(abTesting.scheduleTimer!.isValid)
XCTAssertEqual(round(abTesting.scheduleTimer!.timeInterval), 60)
XCTAssertTrue(abTesting.scheduledTimer!.isValid)
XCTAssertEqual(round(abTesting.scheduledTimer!.timeInterval), 60)
expectation.fulfill()
}

Expand Down

0 comments on commit 629db96

Please sign in to comment.