Files
NetNewsWire/iOS/AppDelegate.swift
T

513 lines
15 KiB
Swift
Raw Normal View History

//
// AppDelegate.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
@preconcurrency import BackgroundTasks
import os
import WidgetKit
import RSCore
2019-04-24 07:30:35 -05:00
import RSWeb
import Account
import Articles
import Secrets
import ErrorLog
2026-05-29 10:46:00 -07:00
import Images
2025-11-18 16:39:51 -08:00
@MainActor var appDelegate: AppDelegate!
2025-11-18 16:39:51 -08:00
@main
2025-11-18 20:31:25 -08:00
@MainActor final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UnreadCountProvider {
2025-11-05 11:22:10 -08:00
2025-11-03 21:32:24 -08:00
private let backgroundTaskDispatchQueue = DispatchQueue.init(label: "BGTaskScheduler")
2019-05-20 13:51:08 -05:00
var shuttingDown = false {
didSet {
if shuttingDown {
2025-11-03 21:32:24 -08:00
ArticleStatusSyncTimer.shared.stop()
2019-05-20 13:51:08 -05:00
}
}
}
2025-11-05 11:22:10 -08:00
nonisolated private static let logger = Logger(subsystem: Logger.nnwSubsystem, category: "Application")
2024-12-30 15:17:20 -08:00
var unreadCount = 0 {
didSet {
if unreadCount != oldValue {
postUnreadCountDidChangeNotification()
updateBadge()
}
}
}
2025-11-05 11:22:10 -08:00
var isSyncArticleStatusRunning = false
var isWaitingForSyncTasks = false
2025-11-05 11:22:10 -08:00
override init() {
super.init()
appDelegate = self
2025-11-05 11:37:16 -08:00
AccountManager.shared.start()
2025-11-05 11:22:10 -08:00
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountRefreshDidFinish(_:)), name: .AccountRefreshDidFinish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUnreadCountDisplaySettingDidChange(_:)), name: .unreadCountDisplaySettingDidChange, object: nil)
}
2025-11-05 11:22:10 -08:00
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AppDefaults.registerDefaults()
2026-05-29 10:46:00 -07:00
FaviconGenerator.templateImage = Assets.Images.faviconTemplate
WebViewConfiguration.resolveBrowserUserAgent()
Task {
await WebViewConfiguration.compileContentBlockingRules()
}
let isFirstRun = AppDefaults.isFirstRun
if isFirstRun {
Self.logger.info("Is first run.")
}
2025-11-05 11:22:10 -08:00
if isFirstRun && !AccountManager.shared.anyAccountHasAtLeastOneFeed() {
let localAccount = AccountManager.shared.defaultAccount
DefaultFeedsImporter.importDefaultFeeds(account: localAccount)
}
2025-11-05 11:22:10 -08:00
registerBackgroundTasks()
CacheCleaner.purgeIfNecessary()
2019-09-01 16:54:07 -05:00
initializeHomeScreenQuickActions()
2025-11-05 11:22:10 -08:00
DispatchQueue.main.async {
self.unreadCount = AccountManager.shared.unreadCount
// Force the badge to update on launch.
self.updateBadge()
}
2025-11-05 11:22:10 -08:00
// Silent CloudKit pushes don’t need notification permission. setBadgeCount does.
UIApplication.shared.registerForRemoteNotifications()
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { _, _ in }
UNUserNotificationCenter.current().delegate = self
UserNotificationManager.shared.start()
2025-11-05 11:22:10 -08:00
2025-11-18 16:39:51 -08:00
ArticleThemesManager.shared.start()
NetworkMonitor.shared.start()
#if !SKIP_APP_GROUP_ACCESS
ExtensionContainersFile.shared.start()
ExtensionFeedAddRequestFile.shared.start()
#endif
2025-11-05 11:22:10 -08:00
2019-05-20 13:51:08 -05:00
#if DEBUG
2025-11-03 21:32:24 -08:00
ArticleStatusSyncTimer.shared.update()
2019-05-20 13:51:08 -05:00
#endif
2025-11-05 11:22:10 -08:00
return true
2025-11-05 11:22:10 -08:00
}
2025-11-05 11:22:10 -08:00
2026-01-01 18:07:54 -08:00
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
2025-11-05 13:15:36 -08:00
Task { @MainActor in
self.resumeIfNecessary()
2025-11-05 13:15:36 -08:00
await AccountManager.shared.receiveRemoteNotification(userInfo: userInfo)
self.suspendApplication()
completionHandler(.newData)
}
}
2025-11-05 11:22:10 -08:00
2019-06-28 10:28:02 -05:00
func applicationWillTerminate(_ application: UIApplication) {
shuttingDown = true
}
func applicationDidEnterBackground(_ application: UIApplication) {
updateBadge()
}
func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
AppNotification.postLowMemory()
}
private func updateBadge() {
assert(unreadCount == AccountManager.shared.unreadCount)
let badgeCount = AppDefaults.unreadCountDisplay == .count ? unreadCount : 0
UNUserNotificationCenter.current().setBadgeCount(badgeCount)
}
2019-06-28 10:28:02 -05:00
// MARK: Notifications
2025-11-05 11:22:10 -08:00
2019-06-28 10:28:02 -05:00
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is AccountManager {
unreadCount = AccountManager.shared.unreadCount
}
}
2025-11-05 11:22:10 -08:00
2019-06-28 10:28:02 -05:00
@objc func accountRefreshDidFinish(_ note: Notification) {
AppDefaults.lastRefresh = Date()
2019-06-28 10:28:02 -05:00
}
2025-11-05 11:22:10 -08:00
@objc func handleUnreadCountDisplaySettingDidChange(_ notification: Notification) {
updateBadge()
}
2019-06-28 10:28:02 -05:00
// MARK: - API
2025-11-05 11:22:10 -08:00
2026-01-02 17:50:35 -08:00
func manualRefresh(errorHandler: @escaping @Sendable (Error) -> Void) {
let sceneDelegates = UIApplication.shared.connectedScenes.compactMap { $0.delegate as? SceneDelegate }
for sceneDelegate in sceneDelegates {
sceneDelegate.cleanUp(conditional: true)
}
2025-11-16 19:59:48 -08:00
AccountManager.shared.refreshAllWithoutWaiting(errorHandler: errorHandler)
}
2025-11-05 11:22:10 -08:00
/// Un-suspend network activity if it was suspended on background entry.
func resumeIfNecessary() {
AppNotification.postAppDidBecomeActive()
if AccountManager.shared.isSuspended {
AccountManager.shared.resumeAll()
Self.logger.info("Application processing resumed.")
}
}
2025-11-05 11:22:10 -08:00
2019-06-28 10:28:02 -05:00
func prepareAccountsForBackground() {
updateBadge()
#if !SKIP_APP_GROUP_ACCESS
ExtensionFeedAddRequestFile.shared.suspend()
#endif
2026-01-07 15:44:49 -08:00
2025-11-03 21:32:24 -08:00
ArticleStatusSyncTimer.shared.invalidate()
2019-06-19 23:26:03 +08:00
scheduleBackgroundFeedRefresh()
syncArticleStatus()
2025-11-16 19:59:48 -08:00
WidgetDataEncoder.shared?.encode()
waitForSyncTasksToFinish()
}
2024-12-04 17:36:08 -08:00
2019-06-28 10:28:02 -05:00
func prepareAccountsForForeground() {
updateBadge()
#if !SKIP_APP_GROUP_ACCESS
ExtensionFeedAddRequestFile.shared.resume()
#endif
2025-11-03 21:32:24 -08:00
ArticleStatusSyncTimer.shared.update()
if let lastRefresh = AppDefaults.lastRefresh {
if Date() > lastRefresh.addingTimeInterval(15 * 60) {
2025-11-16 19:59:48 -08:00
AccountManager.shared.refreshAllWithoutWaiting(errorHandler: ErrorHandler.log)
2019-06-28 10:28:02 -05:00
} else {
2025-11-16 19:59:48 -08:00
AccountManager.shared.syncArticleStatusAllWithoutWaiting()
}
} else {
2025-11-16 19:59:48 -08:00
AccountManager.shared.refreshAllWithoutWaiting(errorHandler: ErrorHandler.log)
}
2019-04-24 07:30:35 -05:00
}
2025-11-05 11:22:10 -08:00
2025-11-18 19:58:48 -08:00
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
2024-12-07 14:52:38 -08:00
completionHandler([.list, .banner, .badge, .sound])
}
2025-11-05 11:22:10 -08:00
// Wrapper to safely transfer non-Sendable values to MainActor
private struct UnsafeSendable<T>: @unchecked Sendable {
let value: T
}
2025-11-05 11:22:10 -08:00
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
2025-11-05 11:22:10 -08:00
2025-11-18 19:58:48 -08:00
let wrappedResponse = UnsafeSendable(value: response)
let wrappedCompletionHandler = UnsafeSendable(value: completionHandler)
2025-11-05 11:22:10 -08:00
2025-11-18 19:58:48 -08:00
Task { @MainActor in
handle(notificationResponse: wrappedResponse.value)
2025-11-18 19:58:48 -08:00
wrappedCompletionHandler.value()
}
}
private func handle(notificationResponse response: UNNotificationResponse) {
let userInfo = response.notification.request.content.userInfo
switch response.actionIdentifier {
case UserNotificationManager.ActionIdentifier.markAsRead:
handleMarkAsRead(userInfo: userInfo)
case UserNotificationManager.ActionIdentifier.markAsStarred:
handleMarkAsStarred(userInfo: userInfo)
default:
if let sceneDelegate = response.targetScene?.delegate as? SceneDelegate {
sceneDelegate.handle(response)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
sceneDelegate.coordinator.dismissIfLaunchingFromExternalAction()
})
}
}
}
}
2019-09-01 16:54:07 -05:00
// MARK: App Initialization
private extension AppDelegate {
2025-11-05 11:22:10 -08:00
2019-09-01 16:54:07 -05:00
private func initializeHomeScreenQuickActions() {
let unreadTitle = NSLocalizedString("First Unread", comment: "First Unread")
let unreadIcon = UIApplicationShortcutIcon(systemImageName: "chevron.down.circle")
2019-09-01 16:54:07 -05:00
let unreadItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.FirstUnread", localizedTitle: unreadTitle, localizedSubtitle: nil, icon: unreadIcon, userInfo: nil)
2025-11-05 11:22:10 -08:00
2019-09-01 16:54:07 -05:00
let searchTitle = NSLocalizedString("Search", comment: "Search")
let searchIcon = UIApplicationShortcutIcon(systemImageName: "magnifyingglass")
let searchItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowSearch", localizedTitle: searchTitle, localizedSubtitle: nil, icon: searchIcon, userInfo: nil)
2019-09-02 15:45:09 -05:00
let addTitle = NSLocalizedString("Add Feed", comment: "Add Feed")
let addIcon = UIApplicationShortcutIcon(systemImageName: "plus")
let addItem = UIApplicationShortcutItem(type: "com.ranchero.NetNewsWire.ShowAdd", localizedTitle: addTitle, localizedSubtitle: nil, icon: addIcon, userInfo: nil)
2019-09-02 16:05:55 -05:00
UIApplication.shared.shortcutItems = [addItem, searchItem, unreadItem]
2019-09-01 16:54:07 -05:00
}
2025-11-05 11:22:10 -08:00
2019-09-01 16:54:07 -05:00
}
// MARK: Go To Background
private extension AppDelegate {
2025-11-05 11:22:10 -08:00
func waitForSyncTasksToFinish() {
guard !isWaitingForSyncTasks && UIApplication.shared.applicationState == .background else {
return
}
2025-11-05 11:22:10 -08:00
isWaitingForSyncTasks = true
var backgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
/// Make sure this run’s background task is ended exactly once.
func endWaitBackgroundTask() {
guard backgroundTaskIdentifier != .invalid else {
return
}
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}
let waitTask = Task { @MainActor in
let shouldSuspend = await waitToComplete()
isWaitingForSyncTasks = false
if shouldSuspend {
suspendApplication()
}
endWaitBackgroundTask()
}
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "Wait for Sync Tasks") {
waitTask.cancel()
self.suspendApplication()
endWaitBackgroundTask()
Self.logger.info("Accounts wait for progress terminated for running too long.")
}
}
2025-11-05 11:22:10 -08:00
/// Wait for the refresh, status sync, and widget encode to finish. Returns whether the app should suspend.
func waitToComplete() async -> Bool {
while !Task.isCancelled {
guard UIApplication.shared.applicationState == .background else {
Self.logger.info("App came back to foreground, no longer waiting.")
return false
}
if AccountManager.shared.refreshInProgress || isSyncArticleStatusRunning || WidgetDataEncoder.shared?.isRunning ?? false {
Self.logger.info("Waiting for sync to finish…")
try? await Task.sleep(for: .seconds(1))
} else {
Self.logger.info("Refresh progress complete.")
return true
}
}
return false
}
2025-11-05 11:22:10 -08:00
func syncArticleStatus() {
guard !isSyncArticleStatusRunning else {
return
}
2025-11-05 11:22:10 -08:00
isSyncArticleStatusRunning = true
2025-11-05 11:22:10 -08:00
var backgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
/// Make sure this run’s background task is ended exactly once.
func endSyncBackgroundTask() {
guard backgroundTaskIdentifier != .invalid else {
2026-05-26 16:28:46 -07:00
return
}
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}
2025-11-05 11:22:10 -08:00
let syncTask = Task { @MainActor in
2025-11-16 19:59:48 -08:00
await AccountManager.shared.syncArticleStatusAll()
isSyncArticleStatusRunning = false
endSyncBackgroundTask()
}
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "Sync Article Status") {
syncTask.cancel()
endSyncBackgroundTask()
Self.logger.info("Accounts sync processing terminated for running too long.")
}
}
2025-11-05 11:22:10 -08:00
func suspendApplication() {
guard UIApplication.shared.applicationState == .background else {
return
}
2026-04-14 09:37:52 -07:00
guard !AccountManager.shared.isSuspended else {
return
}
2025-11-05 11:22:10 -08:00
AccountManager.shared.suspendNetworkAll()
2026-09-01 08:58:31 -07:00
AccountManager.shared.saveAllIfNeeded()
2021-09-21 09:10:56 +08:00
ArticleThemeDownloader.shared.cleanUp()
AppNotification.postAppDidGoToBackground()
CoalescingQueue.standard.performCallsImmediately()
for scene in UIApplication.shared.connectedScenes {
if let sceneDelegate = scene.delegate as? SceneDelegate {
sceneDelegate.suspend()
}
}
2025-11-05 11:22:10 -08:00
Self.logger.info("Application processing suspended.")
}
2025-11-05 11:22:10 -08:00
}
// MARK: - Background Tasks
2019-06-19 23:26:03 +08:00
2019-04-27 13:54:52 -05:00
private extension AppDelegate {
2019-06-19 23:26:03 +08:00
/// Register all background tasks.
nonisolated func registerBackgroundTasks() {
2019-06-19 23:26:03 +08:00
// Register background feed refresh.
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.ranchero.NetNewsWire.FeedRefresh", using: nil) { task in
2019-06-19 23:26:03 +08:00
self.performBackgroundFeedRefresh(with: task as! BGAppRefreshTask)
}
}
2025-11-05 11:22:10 -08:00
/// Ask the system for the next background app refresh.
/// The actual timing is up to the system.
nonisolated func scheduleBackgroundFeedRefresh() {
// We send this to a dedicated serial queue because as of 11/05/19 on iOS 13.2 the call to the
// task scheduler can hang indefinitely.
2025-11-03 21:32:24 -08:00
backgroundTaskDispatchQueue.async {
do {
let earliestBeginInterval: TimeInterval = 60 * 60
2025-11-18 19:07:17 -08:00
let request = BGAppRefreshTaskRequest(identifier: "com.ranchero.NetNewsWire.FeedRefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: earliestBeginInterval)
try BGTaskScheduler.shared.submit(request)
} catch {
Self.logger.error("Could not schedule app refresh: \(error.localizedDescription)")
}
2019-06-19 23:26:03 +08:00
}
}
2025-11-05 11:22:10 -08:00
nonisolated func performBackgroundFeedRefresh(with task: BGAppRefreshTask) {
2024-12-04 17:36:08 -08:00
2019-06-19 23:26:03 +08:00
scheduleBackgroundFeedRefresh() // schedule next refresh
2024-12-04 17:36:08 -08:00
2025-11-16 19:59:48 -08:00
Self.logger.info("Performing background refresh.")
let refreshTaskIsCompleted = OSAllocatedUnfairLock(initialState: false)
enum RefreshOutcome {
case completed
case noNetwork
case expired
}
/// Make sure task.setTaskCompleted is called exactly once.
func completeRefreshTask(_ outcome: RefreshOutcome) {
let shouldComplete = refreshTaskIsCompleted.withLock { isCompleted -> Bool in
if isCompleted {
return false
}
isCompleted = true
return true
}
guard shouldComplete else {
return
}
let success: Bool
switch outcome {
case .completed:
Self.logger.info("Background refresh completed.")
success = true
case .noNetwork:
Self.logger.info("Background refresh skipped — no network path.")
success = false
case .expired:
Self.logger.info("Background refresh terminated for running too long.")
success = false
}
task.setTaskCompleted(success: success)
}
let refreshTask = Task { @MainActor in
if AccountManager.shared.isSuspended {
AccountManager.shared.resumeAll()
}
let didRefresh = await AccountManager.shared.refreshAll(errorHandler: ErrorHandler.log)
if !Task.isCancelled {
await WidgetDataEncoder.shared?.encodeAndWait()
2019-06-19 23:26:03 +08:00
}
self.suspendApplication()
completeRefreshTask(didRefresh ? .completed : .noNetwork)
2019-06-19 23:26:03 +08:00
}
2024-12-04 17:36:08 -08:00
task.expirationHandler = {
refreshTask.cancel()
completeRefreshTask(.expired)
Task { @MainActor in
2024-12-04 17:36:08 -08:00
self.suspendApplication()
}
2019-06-19 23:26:03 +08:00
}
}
}
2020-12-23 20:15:25 +08:00
// MARK: - Handle Notification Actions
2020-12-23 20:15:25 +08:00
private extension AppDelegate {
func handleMarkAsRead(userInfo: [AnyHashable: Any]) {
handleStatusNotification(userInfo: userInfo, statusKey: .read)
2020-12-23 20:15:25 +08:00
}
2025-11-05 11:22:10 -08:00
2020-12-23 20:15:25 +08:00
func handleMarkAsStarred(userInfo: [AnyHashable: Any]) {
handleStatusNotification(userInfo: userInfo, statusKey: .starred)
}
private func handleStatusNotification(userInfo: [AnyHashable: Any], statusKey: ArticleStatus.Key) {
2026-01-01 18:07:54 -08:00
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable: Any],
2020-12-23 20:15:25 +08:00
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String else {
return
}
resumeIfNecessary()
guard let account = AccountManager.shared.existingAccount(accountID: accountID) else {
assertionFailure("Expected account with \(accountID)")
Self.logger.error("No account with accountID \(accountID) found from status notification")
2020-12-23 20:15:25 +08:00
return
}
2025-11-06 19:42:27 -08:00
Task { @MainActor in
try? await account.markArticles(articleIDs: [articleID], statusKey: statusKey, flag: true)
_ = try? await account.syncArticleStatus()
2025-11-06 19:42:27 -08:00
prepareAccountsForBackground()
suspendApplication()
}
2020-12-23 20:15:25 +08:00
}
}