For a offline realm db(sync to a realm server), is there a way to know:
- How many object are waiting to be sync
- The date of the last sync for a specific object
Thanks!
There's no way to know the synchronization state of a specific Object, but the SyncSession class implements a mechanism to register for notification blocks outlining the overall progress of any current sync operations.
let session = SyncUser.current!.session(for: realmURL)!
let token = session.addProgressNotification(for: .download,
mode: .reportIndefinitely) { progress in
if progress.isTransferComplete {
hideActivityIndicator()
} else {
showActivityIndicator()
}
}
// Much later...
token?.stop()
If you have a specific use-case that could benefit by knowing the sync state of an exact Object, please feel free to open an issue on the Realm Cocoa GitHub outlining its details.
Related
I have been using the following code in my iOS Swift app:
class ProfileController
{
func remove(pid: String, completion: #escaping ErrorCompletionHandler)
{
guard let uid = self.uid else
{
completion(Errors.userIdentifierEmpty)
return
}
let db = Firestore.firestore()
let userDocument = db.collection("profiles").document(uid)
let collection = userDocument.collection("profiles")
let document = collection.document(pid)
document.delete()
{
error in
completion(error)
}
}
}
When the device is online, everything works fine. The completion handler of the deletecall is properly executed. However, when I am offline, I have noticed that the completion handler will not be executed as long as I am offline. As soon as I get back online, the completion handler will be called almost immediately.
I don't want to wait until the user is back online (which could take forever), so I changed the code a little bit and added a ListenerRegistration:
class ProfileController
{
func remove(pid: String, completion: #escaping ErrorCompletionHandler)
{
guard let uid = self.uid else
{
completion(Errors.userIdentifierEmpty)
return
}
let db = Firestore.firestore()
let userDocument = db.collection("profiles").document(uid)
let collection = userDocument.collection("profiles")
let document = collection.document(pid)
var listener: ListenerRegistration?
listener = document.addSnapshotListener(includeMetadataChanges: false)
{
snapshot, error in
listener?.remove() // Immediately remove the snapshot listener so we only receive one notification.
completion(error)
listener = nil
}
document.delete()
}
}
Although this works fine, I am not sure if this is the right way to go. I have read online that a snapshot listener can be used in real-time scenarios, which is not really what I am looking for (or what I need).
Is this the right approach or is there another (better) way? I only want to get notified once (thus I added the includeMetadataChanged property and set it to false). I also remove the ListenerRegistration once the completion handler was called once.
If the first approach does not work properly when being offline - what are the use cases of this approach? Before I change my entire codebase to use listeners, is there any way of executing the completion handler of the first approach when the device is offline?
TL;DR: The second implementation works fine, I am simply unsure if this is the proper way of receiving notifications when the device is offline.
If the first approach does not work properly when being offline - what are the use cases of this approach?
It depends on what you mean by "work properly". The behavior you're observing is exactly as intended. Write operations are not "complete" until they're registered at the server.
However, all writes (that are not transactions) are actually committed locally before they hit the server. These local changes will eventually be synchronized with the server at some point in the future, even if the app is killed and restarted. The change is not lost. You can count on the synchronization of the change to eventually hit the server as long as the user continues to launch the app - this is all you can expect. You can read more about offline persistence in the documentation.
If you need to know if a prior change was synchronized, there is no easy way to determine that if the app was killed and restarted. You could try to query for that data, if you know the IDs of the documents written, and you could check the metadata of the documents to find out the source of the data (cache or server). But in the end, you are really supposed to trust that changes will be synchronized with the server at the earliest convenience.
If your use case requires more granularity of information, please file a feature request with Firebase support.
I am trying to get some data from firebase. Any idea how can I get the latest data (not from cache) when I have persistence enabled? I tried keepSynced; I still get stale data. Is this the correct usage?
userRef = FIRDatabase.database().reference().child("<path>")
userRef.keepSynced(true)
userRef.observeSingleEvent(of: .value, with: { snapshot in
...stale data here...
})
Or the only option is to use observe instead of observeSingleEvent? I don't like the fact that with observe I get the cache data first, and then the event triggers a second time with data from the server. So with observe, when I navigate to this screen, first I see a blank table, then I see the table with stale data, and then I see the table with latest data.
Thanks.
EDIT:
https://stackoverflow.com/a/34487195/1373592 -
This post says keeySynced should work. But it's not working for me. I would like to know if I am doing something wrong.
I retrieve some explanation, I think it might help you in your case :
ObserveSingleEventType with keepSycned will not work if the Firebase
connection cannot be established on time. This is especially true
during appLaunch or in the appDelegate where there is a delay in the
Firebase connection and the cached result is given instead. It will
also not work at times if persistence is enabled and
observeSingleEvent might give the cached data first. In situations
like these, a continuous ObserveEventType is preferred and should be
used if you absolutely need fresh data.
I think you don't have the choice to use a continuous listener. But to avoid performance issues why you don't remove yourself your listeners when you don't it anymore.
Here is an example on how to ALWAYS get latest data from firebase when persistence is turned on. Use observe event, keepSynced on your ref and terminate listener if you don't want to keep it always. After several trials, I came up with this and it is working.
func readFromFB() {
let refHandle: DatabaseHandle?
let ref: DatabaseReference? = firebase.child(nodeName)
ref?.keepSynced(true)
refHandle = ref!.observe(.value, with:
{ snapshot in
if snapshot.exists() {
for item in ((snapshot.value as! NSDictionary).allValues as Array) {
//do whatever tasks
}
}
})
if let rf = ref {
rf.removeObserver(withHandle: refHandle!)
}
}
On start my app I do some http requests, some heavy http requests (downloading some images) and some heavy tasks with UIGraphics (for example doing icon for GMSMarker from two UIImages and other operations with GraphicsContext). It costs some time, so I want to do all that tasks simultaneously. Can you show me best way make it?
On start I have to:
Download and write to local database all devices
Download and write to local database all geofences
Download and write to local database all users
Download and write to local database all positions
Download images for devices, users and geofences
Setup GMSMarkers for devices, users and geofences (after images for that objects will be available - for setting icon of marker)
Code of my login function (it works, but too slow):
func loginPressed(_ sender: UIButton) {
guard
let username = self.usernameTextField.text,
let password = self.passwordTextField.text,
!username.isEmpty,
!password.isEmpty
else {
return
}
self.loginButton.isEnabled = false
self.activityIndicator.startAnimating()
WebService.shared.connect(email: username, password: password) { error, loggedUser in
guard
error == nil,
let loggedUser = loggedUser
else {
self.showAlert(title: "Ошибка подключения", message: error?.localizedDescription ?? "", style: .alert)
self.activityIndicator.stopAnimating()
self.loginButton.isEnabled = true
return
}
DB.users.client.insert(loggedUser)
print("Start loading user photo...")
loggedUser.loadPhoto() { image in
if let image = image {
loggedUser.photo = UIImageJPEGRepresentation(image, 0.0)
}
print("User photo loaded...")
loggedUser.marker = UserMarker(loggedUser, at: CLLocation(latitude: 48.7193900, longitude: 44.50183))
DB.users.client.modify(loggedUser)
}
DB.geofences.server.getAll() { geofences in
DB.devices.server.getAll() { devices in
DB.positions.server.getAll() { positions in
for device in devices {
device.loadPhoto() { image in
if let image = image {
device.photo = UIImageJPEGRepresentation(image, 0.0)
}
if let position = positions.findById(device.positionId) {
device.marker = DeviceMarker(device, at: position)
}
device.attributes.battery = device.lastKnownBattery(in: positions)
}
}
geofences.forEach({$0.marker = GeofenceMarker($0)})
DB.geofences.client.updateAddress(geofences) { geofences in
if DEBUG_LOGS {
print("Geofences with updated addresses: ")
geofences.forEach({print("\($0.name), \($0.address ?? "")")})
}
DB.devices.client.insert(devices)
DB.geofences.client.insert(geofences)
DB.positions.client.insert(positions)
self.activityIndicator.stopAnimating()
WebService.shared.addObserver(DefaultObserver.shared)
self.performSegue(withIdentifier: "toMapController", sender: self)
}
}
}
}
}
}
Not sure it's good idea post here code snippets of all classes and objects, hope you'll get idea.
Any help would be appreciated.
P.S. In case you wonder what is DB, it's database, which consists of two parts - server side and client side for each group of objects, so first task is get all objects from server and write them in memory (in client database)
P.S. I've changed logic from "download everything" on login to "download all I need right now and download rest later". So now after I've got all devices, geofences and positions I'm performing segue to MapController, on which I show all those objects. Just after login I'm showing deviceMarkers (GMSMarker) with default iconView. SO question is - can I after show map with all objects start download photos of devices in background and refresh markers with that photos after that (in main thread of course)?
Network requests are asynchronous by default, so what you are asking for has already the intended behavior.
You can, however, make your life much more simple by using a Promises library such as then.
An example usage might look like:
login(email: "foo#bar.com", password: "pa$$w0rd")
.whenAll(syncDevices(), syncGeofences(), syncUsers(), syncPositions(), syncImages())
.onError { err in
// process error
}
.finally {
// update UI
}
Your login function is slow because you are downloading AND writing to disk (as you mentioned in your question) "all" the data in your closures (geofences, devices and/or positions). Furthermore, all your operations are being executed in the main thread. You should never do I/O (networking, writing to disk) in the main thread, as this thread is used mainly for UI updates. You should offload the expensive tasks to another thread using GCD.
Also, it is worth mentioning that writing to disk is a relatively slow operation, especially if you are doing it for EVERY item you are downloading.
I would recommend you to JUST download any data to be displayed and then use an async task in a DispatchQueue (GCD) to persist the data downloaded to disk AFTER you've displayed the data in your UI.
I am not sure what the DB.geofences.server.getAll() lines do for geofences, devices and positions (in regards to how you handle your networking or database fetching), so I cannot advice you on that. What I can advice you on, is to structure your code the following way:
When user logs in, do the validation against the DB (remote) and guard against a valid login. Transition to your next view controller next (don't execute all your logic), since I can see that you are delegating way too much responsibility to your login action (for your login button).
From that second view controller, get your data through networking calls asynchronously on another thread using a .UserInitiated priority (to get results fast).
After doing all your networking operations, call DispatchQueue.main.async { ... } to update your UI Asynchronously in the main thread with the data you just got.
AFTER you've displayed the downloaded data, you can persist it to your local DB, ideally using another DispatchQueue async task.
If anything I said above does not make any sense to you, please read AppCoda's article about GCD here and RayWenderlich's GCD article here. They will give you the basic knowledge about GCD in iOS. Once you've done that, come back and try to structure your code the way I recommended above.
I hope this helps!
I have a windows service, running workflows. The workflows are XAMLs loaded from database (users can define their own workflows using a rehosted designer). It is configured with one instance of the SQLWorkflowInstanceStore, to persist workflows when becoming idle. (It's basically derived from the example code in \ControllingWorkflowApplications from Microsoft's WCF/WF samples).
But sometimes I get an error like below:
System.Runtime.DurableInstancing.InstanceOwnerException: The execution of an InstancePersistenceCommand was interrupted because the instance owner registration for owner ID 'a426269a-be53-44e1-8580-4d0c396842e8' has become invalid. This error indicates that the in-memory copy of all instances locked by this owner have become stale and should be discarded, along with the InstanceHandles. Typically, this error is best handled by restarting the host.
I've been trying to find the cause, but it is hard to reproduce in development, on production servers however, I get it once in a while. One hint I found : when I look at the LockOwnersTable, I find the LockOnwersTable lockexpiration is set to 01/01/2000 0:0:0 and it's not getting updated anymore, while under normal circumstances the should be updated every x seconds according to the Host Lock Renewal period...
So , why whould SQLWorkflowInstanceStore stop renewing this LockExpiration and how can I detect the cause of it?
This happens because there are procedures running in the background and trying to extend the lock of the instance store every 30 seconds, and it seems that once the connection fail connecting to the SQL service it will mark this instance store as invalid.
you can see the same behaviour if you delete the instance store record from [LockOwnersTable] table.
The proposed solution is when this exception fires, you need to free the old instance store and initialize a new one
public class WorkflowInstanceStore : IWorkflowInstanceStore, IDisposable
{
public WorkflowInstanceStore(string connectionString)
{
_instanceStore = new SqlWorkflowInstanceStore(connectionString);
InstanceHandle handle = _instanceStore.CreateInstanceHandle();
InstanceView view = _instanceStore.Execute(handle,
new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
handle.Free();
_instanceStore.DefaultInstanceOwner = view.InstanceOwner;
}
public InstanceStore Store
{
get { return _instanceStore; }
}
public void Dispose()
{
if (null != _instanceStore)
{
var deleteOwner = new DeleteWorkflowOwnerCommand();
InstanceHandle handle = _instanceStore.CreateInstanceHandle();
_instanceStore.Execute(handle, deleteOwner, TimeSpan.FromSeconds(10));
handle.Free();
}
}
private InstanceStore _instanceStore;
}
you can find the best practices to create instance store handle in this link
Workflow Instance Store Best practices
This is an old thread but I just stumbled on the same issue.
Damir's Corner suggests to check if the instance handle is still valid before calling the instance store. I hereby quote the whole post:
Certain aspects of Workflow Foundation are still poorly documented; the persistence framework being one of them. The following snippet is typically used for setting up the instance store:
var instanceStore = new SqlWorkflowInstanceStore(connectionString);
instanceStore.HostLockRenewalPeriod = TimeSpan.FromSeconds(30);
var instanceHandle = instanceStore.CreateInstanceHandle();
var view = instanceStore.Execute(instanceHandle,
new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(10));
instanceStore.DefaultInstanceOwner = view.InstanceOwner;
It's difficult to find a detailed explanation of what all of this
does; and to be honest, usually it's not necessary. At least not,
until you start encountering problems, such as InstanceOwnerException:
The execution of an InstancePersistenceCommand was interrupted because
the instance owner registration for owner ID
'9938cd6d-a9cb-49ad-a492-7c087dcc93af' has become invalid. This error
indicates that the in-memory copy of all instances locked by this
owner have become stale and should be discarded, along with the
InstanceHandles. Typically, this error is best handled by restarting
the host.
The error is closely related to the HostLockRenewalPeriod property
which defines how long obtained instance handle is valid without being
renewed. If you try monitoring the database while an instance store
with a valid instance handle is instantiated, you will notice
[System.Activities.DurableInstancing].[ExtendLock] being called
periodically. This stored procedure is responsible for renewing the
handle. If for some reason it fails to be called within the specified
HostLockRenewalPeriod, the above mentioned exception will be thrown
when attempting to persist a workflow. A typical reason for this would
be temporarily inaccessible database due to maintenance or networking
problems. It's not something that happens often, but it's bound to
happen if you have a long living instance store, e.g. in a constantly
running workflow host, such as a Windows service.
Fortunately it's not all that difficult to fix the problem, once you
know the cause of it. Before using the instance store you should
always check, if the handle is still valid; and renew it, if it's not:
if (!instanceHandle.IsValid)
{
instanceHandle = instanceStore.CreateInstanceHandle();
var view = instanceStore.Execute(instanceHandle,
new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(10));
instanceStore.DefaultInstanceOwner = view.InstanceOwner;
}
It's definitely less invasive than the restart of the host, suggested
by the error message.
you have to be sure about expiration of owner user
here how I am used to handle this issue
public SqlWorkflowInstanceStore SetupSqlpersistenceStore()
{
SqlWorkflowInstanceStore sqlWFInstanceStore = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["DB_WWFConnectionString"].ConnectionString);
sqlWFInstanceStore.InstanceCompletionAction = InstanceCompletionAction.DeleteAll;
InstanceHandle handle = sqlWFInstanceStore.CreateInstanceHandle();
InstanceView view = sqlWFInstanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
handle.Free();
sqlWFInstanceStore.DefaultInstanceOwner = view.InstanceOwner;
return sqlWFInstanceStore;
}
and here how you can use this method
wfApp.InstanceStore = SetupSqlpersistenceStore();
wish this help
I'm building a WP7 app, and I'm now at the point of handling the tombstoning part of it.
What I am doing is saving the viewmodel of the page in the Page.State bag when the NavigatedFrom event occurs, and reading it back in the NavigatedTo (with some check to detect whether I should read from the bag or read from the real live data of the application).
First my VM was just a wrapper to the domain model
public string Nome
{
get
{
return _dm.Nome;
}
set
{
if (value != _dm.Nome)
{
_dm.Nome= value;
NotifyPropertyChanged("Nome");
}
}
}
But this didn't always work because when saving to the bag and then reading back, the domain model was not deserialized correctly.
Then I changed my VM implementation to be just a copy of the properties I needed from the DM:
public string Nome
{
get
{
return _nome;
}
set
{
if (value !=nome)
{
_nome= value;
NotifyPropertyChanged("Nome");
}
}
}
and with the constructor that does:
_nome = dm.Nome;
And now it works, but I was not sure if this is the right approach.
Thx
Simone
Any transient state information should be persisted in the Application.Deactivated event and then restored in the Application.Activated event for tombstoning support.
If you need to store anything between application sessions then you could use the Application.Closing event, but depending on what you need to store, you could just store it whenever it changes. Again, depending on what you need to store, you can either restore it in the Application.Launching event, or just read it when you need it.
The approach that you take depends entirely on your application's requirements and the method and location that you store your data is also up to you (binary serialization to isolated storage is generally accepted is being the fastest).
I don't know the details of your application, but saving and restoring data in NavigatedFrom/NavigatedTo is unlikely to be the right place to do it if you are looking to implement support for tombstoning.
I'd recommend against making a copy of part of the model as when tombstoning you'd (probably) need to persist both the full (app level) model and the page level copy when handling tombstoning.
Again the most appropriate solution will depend on the complexity of your application and the models it uses.
Application.Activated/Deactivated is a good place to handle tombstoning.
See why OnNavigatedTo/From may not be appropriate for your needs here.
How to correctly handle application deactivation and reactivation - Peter Torr's Blog
Execution Model Overview for Windows Phone