Use AppStorage dynamic property instead of direct UserDefaults update

Known issue: the menubar File > Reload From Server command will not update based on changes to model.account.isLoggedIn, but instead defaults to whatever the value was on app launch. Filed as FB8918303 with Apple.
This commit is contained in:
Angelo Stavrow 2020-11-26 12:05:20 -05:00
parent 7398c1d3cf
commit 7cb7fa3017
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE
3 changed files with 6 additions and 8 deletions

View File

@ -1,4 +1,4 @@
import Foundation
import SwiftUI
import WriteFreely
enum AccountError: Error {
@ -30,8 +30,8 @@ extension AccountError: LocalizedError {
}
struct AccountModel {
@AppStorage("isLoggedIn") var isLoggedIn: Bool = false
private let defaults = UserDefaults.standard
let isLoggedInFlag = "isLoggedInFlag"
let usernameStringKey = "usernameStringKey"
let serverStringKey = "serverStringKey"
@ -39,13 +39,11 @@ struct AccountModel {
var username: String = ""
private(set) var user: WFUser?
private(set) var isLoggedIn: Bool = false
mutating func login(_ user: WFUser) {
self.user = user
self.username = user.username ?? ""
self.isLoggedIn = true
defaults.set(true, forKey: isLoggedInFlag)
defaults.set(user.username, forKey: usernameStringKey)
defaults.set(server, forKey: serverStringKey)
}
@ -53,13 +51,11 @@ struct AccountModel {
mutating func logout() {
self.user = nil
self.isLoggedIn = false
defaults.set(false, forKey: isLoggedInFlag)
defaults.removeObject(forKey: usernameStringKey)
defaults.removeObject(forKey: serverStringKey)
}
mutating func restoreState() {
isLoggedIn = defaults.bool(forKey: isLoggedInFlag)
server = defaults.string(forKey: serverStringKey) ?? ""
username = defaults.string(forKey: usernameStringKey) ?? ""
}

View File

@ -60,8 +60,9 @@ struct ContentView: View {
model.fetchUserPosts()
}
}, label: { Image(systemName: "arrow.clockwise") })
.padding(.leading, sidebarIsHidden ? 8 : 0)
.animation(.linear)
.disabled(!model.account.isLoggedIn)
.padding(.leading, sidebarIsHidden ? 8 : 0)
.animation(.linear)
}
ToolbarItem(placement: .status) {
if let selectedPost = model.selectedPost {

View File

@ -37,6 +37,7 @@ struct WriteFreely_MultiPlatformApp: App {
model.fetchUserPosts()
}
}
.disabled(!model.account.isLoggedIn)
.keyboardShortcut("r", modifiers: [.command])
}
#if os(macOS)