Firestore 禁用缓存 - Swift 单例
Firestore Disable Cache - Swift Singleton
创建具有 Firestore 属性 的 swift 单例时,如何将其设置为不缓存。出于某种原因,我无法让我的 init 工作。不断收到不能使用实例成员的投诉? (被告知实例成员 'db' 不能用在类型 'HCFireStoreService' 上;您是想使用这种类型的值吗?
class HCFireStoreService {
var db = Firestore.firestore()
static let instance: HCFireStoreService = {
let sharedInstance = HCFireStoreService()
let settings = FirestoreSettings()
settings.isPersistenceEnabled = false
db.settings = settings
return sharedInstance
}()
}
如果您不注意执行顺序,使用单例模式配置 Firestore 可能会很棘手。我会避免使用 Firestore 的单例模式,但如果你想让它工作,这是一种方法:
class HCFireStoreService {
static let shared = HCFireStoreService()
private let db = Firestore.firestore()
private init() {}
func configure() {
let settings = FirestoreSettings()
settings.isPersistenceEnabled = false
db.settings = settings
}
func someMethod() {
db.document("yyy/xxx").getDocument { (snapshot, error) in
print("xxx")
}
}
}
要使其正常工作,您必须在配置 Firebase 之后和与数据库交互之前实例化此 class(首次使用共享实例)。因此,如果您在 App Delegate 中配置 Firestore,然后只需配置单例,然后您就可以自由使用它的方法了。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
HCFireStoreService.shared.configure()
}
HCFireStoreService.shared.someMethod()
创建具有 Firestore 属性 的 swift 单例时,如何将其设置为不缓存。出于某种原因,我无法让我的 init 工作。不断收到不能使用实例成员的投诉? (被告知实例成员 'db' 不能用在类型 'HCFireStoreService' 上;您是想使用这种类型的值吗?
class HCFireStoreService {
var db = Firestore.firestore()
static let instance: HCFireStoreService = {
let sharedInstance = HCFireStoreService()
let settings = FirestoreSettings()
settings.isPersistenceEnabled = false
db.settings = settings
return sharedInstance
}()
}
如果您不注意执行顺序,使用单例模式配置 Firestore 可能会很棘手。我会避免使用 Firestore 的单例模式,但如果你想让它工作,这是一种方法:
class HCFireStoreService {
static let shared = HCFireStoreService()
private let db = Firestore.firestore()
private init() {}
func configure() {
let settings = FirestoreSettings()
settings.isPersistenceEnabled = false
db.settings = settings
}
func someMethod() {
db.document("yyy/xxx").getDocument { (snapshot, error) in
print("xxx")
}
}
}
要使其正常工作,您必须在配置 Firebase 之后和与数据库交互之前实例化此 class(首次使用共享实例)。因此,如果您在 App Delegate 中配置 Firestore,然后只需配置单例,然后您就可以自由使用它的方法了。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
HCFireStoreService.shared.configure()
}
HCFireStoreService.shared.someMethod()