Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/bg fetch #1303

Draft
wants to merge 11 commits into
base: trunk
Choose a base branch
from
59 changes: 59 additions & 0 deletions Simplenote/SPAppDelegate+Extensions.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import BackgroundTasks


// MARK: - Initialization
Expand Down Expand Up @@ -405,3 +406,61 @@ extension SPAppDelegate {
EditorFactory.shared.scrollPositionCache.cleanup(keeping: allIdentifiers)
}
}

// MARK: - Background Fetch
//
@available(iOS 13.0, *)
extension SPAppDelegate {
@objc
func registerBackgroundRefreshTask() {
guard BuildConfiguration.current == .debug else {
return
}

NSLog("Registered background task with identifier \(BackgroundRefreshConstants.bgTaskIdentifier)")
BGTaskScheduler.shared.register(forTaskWithIdentifier: BackgroundRefreshConstants.bgTaskIdentifier, using: .main) { task in
guard let task = task as? BGAppRefreshTask else {
return
}
self.handleAppRefresh(task: task)
}
}

private func handleAppRefresh(task: BGAppRefreshTask) {
NSLog("Did fire handle app refresh")
guard BuildConfiguration.current == .debug else {
return
}

NSLog("Background refresh intiated")
scheduleAppRefresh()

DispatchQueue.main.asyncAfter(deadline: .now() + BackgroundRefreshConstants.timeOut) {
NSLog("Background refresh finishing")
task.setTaskCompleted(success: true)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also set an expiration handler, because according to Apple Docs:

If you don’t set an expiration handler, the system will mark your task as complete and unsuccessful instead of sending a warning.

If we set an expiration handler I think there is no reason to have our own timeout.


Other ideas:

  • We can extract all BG related code to a separate class to clean up app delegate
  • To avoid always waiting for BG task to expire we can try to be smart: re-set a timer for x seconds on every change that we receive (- (void)bucket:(SPBucket *)bucket didChangeObjectForKey:(NSString *)key....). So when all changes are received and processed, we wait a bit and finish BG task.


@objc
func scheduleAppRefresh() {
guard BuildConfiguration.current == .debug else {
return
}

NSLog("Background refresh scheduled")
let request = BGAppRefreshTaskRequest(identifier: BackgroundRefreshConstants.bgTaskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: BackgroundRefreshConstants.earliestBeginDate)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Couldn't schedule app refersh: \(error)")
}
}
}

private struct BackgroundRefreshConstants {
static let earliestBeginDate = TimeInterval(1800.0) //30 minutes
static let timeOut = TimeInterval(25)
static let bundleIdentifier = Bundle.main.bundleIdentifier ?? "com.codality.NotationalFlow"
static let bgTaskIdentifier = bundleIdentifier + ".refresh"
}
10 changes: 10 additions & 0 deletions Simplenote/SPAppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,11 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
[self showPasscodeLockIfNecessary];
}

// Register background refresh task to system
if (@available(iOS 13.0, *)) {
[self registerBackgroundRefreshTask];
}

// Index (All of the) Spotlight Items if the user upgraded
[self indexSpotlightItemsIfNeeded];

Expand All @@ -190,6 +195,11 @@ - (void)applicationDidEnterBackground:(UIApplication *)application

[self showPasscodeLockIfNecessary];
[self cleanupScrollPositionCache];

// Schedule background refresh
if (@available(iOS 13.0, *)) {
[self scheduleAppRefresh];
}
}

- (void)applicationWillEnterForeground:(UIApplication *)application
Expand Down
8 changes: 8 additions & 0 deletions Simplenote/Simplenote-Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@
<string>com.codality.NotationalFlow.newNote</string>
<string>com.codality.NotationalFlow.openNote</string>
</array>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIPrerenderedIcon</key>
Expand All @@ -86,6 +90,10 @@
<array>
<string>armv7</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).refresh</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
Expand Down