问题
I have request data which was about 7MB after it has downloaded the json string,means the json string is about 7MB.After it has downloaded,I would like to save the data into realm model object(table) with progress like
(1/7390) to (7390/7390) -> (data which is inserted/total data to be inserted)
I am using Alamofire as HTTPClient at my app.So,how to insert data with progress into my realm object model after it has downloaded from server?Any help cause I am a beginner.
I wont show the data model exactly,so,any example is appreciated.Let say my json string is.
{
{
name : Smith,
age : 23,
address : New York
},
{
name : Adam,
age : 22,
address : Maimi
},
{
name : Johnny,
age : 33,
address : Las Vegas
},
... about 7392 records
}
回答1:
Supposing you have a label for do this.
Ok.
Supposing you using MVVM pattern too.
Ok.
ViewController has label and "observe"(*) the ViewModel property 'progress'
ViewModel has property 'progress'
class ViewModel: NSObject {
dynamic var progress: Int = 0
func save(object object: Object) {
do {
let realm = try Realm()
try realm.write({ () -> Void in
// Here your operations on DB
self.progress += 1
})
} catch let error as NSError {
ERLog(what: error)
}
}
}
In this way viewController is notified when "progress" change and you can update UI.
Your VC should have a method like this, called by viewDidLoad for instance:
private func setupObservers() {
RACObserve(self.viewModel, keyPath: "progress").subscribeNext { (next: AnyObject!) -> Void in
if let newProgress = next as? Int {
// Here update label
}
}
}
Where RACObserve is a global function:
import Foundation
import ReactiveCocoa
func RACObserve(target: NSObject!, keyPath: String) -> RACSignal {
return target.rac_valuesForKeyPath(keyPath, observer: target)
}
(*) You can use ReactiveCocoa for instance.
回答2:
Katsumi from Realm here. First, Realm has no way to know the total amount of data. So calculating progress and notifying it should be done in your code.
A total is a count of results array. Store count
as a local variable. Then define progress
variable to store the number of persisted. progress
should be incremented every save an object to the Realm. Then notify the progress.
let count = results.count // Store count of results
if count > 0{
if let users = results.array {
let progress = 0 // Number of persisted
let realm = try! Realm()
try realm.write {
for user in users{
let userList=UserList()
[...]
realm.add(userList,update: true)
progress += 1 // After save, increment progress
notify(progress, total: count)
}
}
}
}
So there are several ways to notify the progress. Here we use NSNotificationCenter
for example:
func notify(progress: Int, total: Int) {
NSNotificationCenter
.defaultCenter()
.postNotificationName("ProgressNotification", object: self, userInfo: ["progress": progress, "total": total])
}
来源:https://stackoverflow.com/questions/36030347/inserting-data-into-realm-db-with-progress