1
0
mirror of https://github.com/mastodon/mastodon-ios.git synced 2025-02-06 20:33:20 +01:00
Nathan Mattes 45028373d4 Store accounts in container (IOS-192)
In case you see an empty app: Add your account again.

Background: As we need access to the account from the extensions and the extensions can't access the documents-directory but the group-container, well, the accounts will live there from now on.
2024-01-02 23:05:25 +01:00

57 lines
1.6 KiB
Swift

// Copyright © 2023 Mastodon gGmbH. All rights reserved.
import Foundation
import MastodonSDK
public extension FileManager {
func store(account: Mastodon.Entity.Account, forUserID userID: UserIdentifier) {
var accounts = accounts(for: userID)
if let index = accounts.firstIndex(of: account) {
accounts.remove(at: index)
}
accounts.append(account)
storeJSON(accounts, userID: userID)
}
func accounts(for userId: UserIdentifier) -> [Mastodon.Entity.Account] {
guard let sharedDirectory else { return [] }
let accountPath = Persistence.accounts(userId).filepath(baseURL: sharedDirectory)
guard let data = try? Data(contentsOf: accountPath) else { return [] }
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601
do {
let accounts = try jsonDecoder.decode([Mastodon.Entity.Account].self, from: data)
return accounts
} catch {
return []
}
}
}
private extension FileManager {
private func storeJSON(_ encodable: Encodable, userID: UserIdentifier) {
guard let sharedDirectory else { return }
let jsonEncoder = JSONEncoder()
jsonEncoder.dateEncodingStrategy = .iso8601
do {
let data = try jsonEncoder.encode(encodable)
let accountsPath = Persistence.accounts( userID).filepath(baseURL: sharedDirectory)
try data.write(to: accountsPath)
} catch {
debugPrint(error.localizedDescription)
}
}
}