Remember notifications tab after app restart (#1048)

This commit is contained in:
Marcus Kida 2023-05-15 14:12:41 +02:00 committed by GitHub
parent c7347e7f1f
commit 3a05799df8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 4 deletions

View File

@ -25,8 +25,25 @@ final class NotificationViewModel {
// output
let scopes = NotificationTimelineViewModel.Scope.allCases
@Published var viewControllers: [UIViewController] = []
@Published var currentPageIndex = 0
@Published var currentPageIndex = 0 {
didSet {
lastPageIndex = currentPageIndex
}
}
private var lastPageIndex: Int {
get {
UserDefaults.shared.getLastSelectedNotificationsTab(
accessToken: authContext.mastodonAuthenticationBox.userAuthorization.accessToken
)
}
set {
UserDefaults.shared.setLastSelectedNotificationsTab(
accessToken: authContext.mastodonAuthenticationBox.userAuthorization.accessToken,
value: newValue
)
}
}
init(context: AppContext, authContext: AuthContext) {
self.context = context
@ -58,7 +75,14 @@ extension NotificationViewModel: PageboyViewControllerDataSource {
}
func defaultPage(for pageboyViewController: PageboyViewController) -> PageboyViewController.Page? {
return .first
guard
let pageCount = pageboyViewController.pageCount,
pageCount > 1,
(0...(pageCount - 1)).contains(lastPageIndex)
else {
return .first /// this should never happen, but in case we somehow manage to acquire invalid data in `lastPageIndex` let's make sure not to crash the app.
}
return .at(index: lastPageIndex)
}
}

View File

@ -20,6 +20,7 @@ extension UserDefaults {
}
private static let notificationCountKeyPrefix = "notification_count"
private static let notificationsLastTabIndexKeyPrefix = "last_notification_tab_index"
public func getNotificationCountWithAccessToken(accessToken: String) -> Int {
let prefix = UserDefaults.notificationCountKeyPrefix
@ -38,6 +39,17 @@ extension UserDefaults {
setNotificationCountWithAccessToken(accessToken: accessToken, value: count + 1)
}
@objc public func getLastSelectedNotificationsTab(accessToken: String) -> Int {
let prefix = UserDefaults.notificationsLastTabIndexKeyPrefix
let key = UserDefaults.deriveKey(from: accessToken, prefix: prefix)
return integer(forKey: key)
}
@objc public func setLastSelectedNotificationsTab(accessToken: String, value: Int) {
let prefix = UserDefaults.notificationsLastTabIndexKeyPrefix
let key = UserDefaults.deriveKey(from: accessToken, prefix: prefix)
setValue(value, forKey: key)
}
}
extension UserDefaults {