当创建一个有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之后和与数据库交互之前实例化该类(第一次使用共享实例)。因此,如果你在App Delegate中配置Firestore,那么之后只需简单地配置单例,然后你就可以自由地使用它的方法了。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
HCFireStoreService.shared.configure()
}
HCFireStoreService.shared.someMethod()