我在我的一個iOS項目中使用Realm Swift,其中一個應用程序要求是允許多個用戶的數據共存。由於Realm無法識別與該用戶關聯的領域數據庫文件,因此在同一用戶登錄時我遇到了問題。例如:因此,每次UserA在註銷後重新登錄,都會爲UserA生成一個新的Realm文件。 UserA註銷並且UserB登錄時不會發生這種情況,然後UserB註銷並且UserA登錄。Realm Swift Multi用戶登錄
UserA(註銷) - > UserB(登錄) - > UseB(註銷) - > UserA(登錄)[This作品]
UserA(登錄) - > UserA(註銷) - > UserA(登錄)[這不起作用,將創建一個新的Realm文件,如果存在遷移,請嘗試! Realm()也失敗了)
我的AppDelegate代碼在應用程序中:didFinishLaunchingWithOptions看起來像下面這樣。
func setDefaultRealmForUser() {
var config = Realm.Configuration()
// Inside your application(application:didFinishLaunchingWithOptions:)
let currentLoggedInRegId = NSUserDefaults.standardUserDefaults().valueForKey(Constants.UserDefaults.CurrentLoggedInRegId)
if currentLoggedInRegId != nil {
let registrationId = currentLoggedInRegId as! String
// Use the default directory, but replace the filename with the username
config.fileURL = config.fileURL!.URLByDeletingLastPathComponent?
.URLByAppendingPathComponent("\(registrationId).realm")
}
// Set this as the configuration used for the default Realm
Realm.Configuration.defaultConfiguration = config
}
,併成功我loginViewController代碼如下所示
func setDefaultRealmForUser(onComplete:()->()) {
var config = Realm.Configuration()
let currentLoggedInRegId = NSUserDefaults.standardUserDefaults().valueForKey(Constants.UserDefaults.CurrentLoggedInRegId)
if currentLoggedInRegId != nil {
let registrationId = currentLoggedInRegId as! String
// Use the default directory, but replace the filename with the username
config.fileURL = config.fileURL!.URLByDeletingLastPathComponent?
.URLByAppendingPathComponent("\(registrationId).realm")
}
// Set this as the configuration used for the default Realm
Realm.Configuration.defaultConfiguration = config
onComplete()
}
更新:我已爲時間通過加載用戶域的配置,它看起來像之前加載默認的境界而努力下面的代碼:
func reloadRealmWithDefault(onComplete:()->()) -> (Void) {
var config = Realm.Configuration()
let defaultRealm = "default"
// Use the default directory, but replace the filename with the username
config.fileURL = config.fileURL!.URLByDeletingLastPathComponent?
.URLByAppendingPathComponent("\(defaultRealm).realm")
// Set this as the configuration used for the default Realm
Realm.Configuration.defaultConfiguration = config
onComplete()
}
但我不使用這種方法,因爲它更是一個黑客的工作完全滿意。
做多用戶登錄場景的最佳方式是什麼?