Skip to content

Commit

Permalink
Merge pull request #134 from theleftbit/more-appgroup
Browse files Browse the repository at this point in the history
Add AppGroup support for UserDefaultsBacked
  • Loading branch information
piercifani authored Aug 16, 2022
2 parents 0160b23 + e11bc94 commit 429545a
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions Sources/BSWFoundation/PropertyWrappers/UserDefaultsBacked.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,40 @@ import Foundation
public class UserDefaultsBacked<T> {
private let key: String
private let defaultValue: T?

public init(key: String, defaultValue: T? = nil) {
private let store: UserDefaults

public init(key: String, defaultValue: T? = nil, appGroupID: String? = nil) {
self.key = key
self.defaultValue = defaultValue
self.store = {
if let appGroupID = appGroupID {
return UserDefaults(suiteName: appGroupID)!
} else {
return UserDefaults.standard
}
}()
}

public var wrappedValue: T? {
get {
guard let value = UserDefaults.standard.object(forKey: key) as? T else {
guard let value = self.store.object(forKey: key) as? T else {
return defaultValue
}
return value
} set {
if newValue != nil {
UserDefaults.standard.set(newValue, forKey: key)
self.store.set(newValue, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
self.store.removeObject(forKey: key)
}
UserDefaults.standard.synchronize()
self.store.synchronize()
}
}
}

public extension UserDefaultsBacked {
func reset() {
UserDefaults.standard.removeObject(forKey: key)
self.store.removeObject(forKey: key)
}
}

Expand All @@ -42,30 +50,38 @@ public extension UserDefaultsBacked {
public class CodableUserDefaultsBacked<T: Codable> {
private let key: String
private let defaultValue: T?
private let store: UserDefaults

public init(key: String, defaultValue: T? = nil) {
public init(key: String, defaultValue: T? = nil, appGroupID: String? = nil) {
self.key = key
self.defaultValue = defaultValue
self.store = {
if let appGroupID = appGroupID {
return UserDefaults(suiteName: appGroupID)!
} else {
return UserDefaults.standard
}
}()
}

public var wrappedValue: T? {
get {
guard let data = UserDefaults.standard.data(forKey: key) else {
guard let data = self.store.data(forKey: key) else {
return defaultValue
}
return try? JSONDecoder().decode(T.self, from: data)
} set {
guard let data = try? JSONEncoder().encode(newValue) else {
return
}
UserDefaults.standard.set(data, forKey: key)
UserDefaults.standard.synchronize()
self.store.set(data, forKey: key)
self.store.synchronize()
}
}
}

public extension CodableUserDefaultsBacked {
func reset() {
UserDefaults.standard.removeObject(forKey: key)
self.store.removeObject(forKey: key)
}
}

0 comments on commit 429545a

Please sign in to comment.