I have to create an application that has functionality similar to the contacts app. You can add a contact on the client's iPhone and it should get uploaded onto the client's iPad. If the client updates the contact on their iPad, it should get updated on their iPhone.
Most of this is fairly straight forward. I am using Parse.com as my back end and saving contacts locally with Core Data. The only problem I'm encountering is managing contacts when the user is offline.
Let's say I have an iPhone and an iPad. Both of them currently have the same version of the online database. My iPhone is now offline. It is 9AM.
At 10AM I update the phone number for a contact on my iPad. It saves the change locally and online. At 11AM I update the email address for the same contact on my iPhone but I'm still offline.
At noon, my iPhone connects to the internet and checks the server for changes. It sees that its changes are more recent than the latest update (checking an updatedAt timestamp property), so instead of downloading the new phone number for the contact (which is "obsolete"), it overrides the phone number along with the email address (updates the new phone number to the old version it has because it was offline during the phone number update at 10AM and its changes are supposedly more recent).
How am I supposed to manage the online/offline problems encountered such as the one above? A solution I can think of would be to keep updated timestamps on every attribute for a contact instead of just a general updatedAt property for the entire contact, e.g. when was first name updated, when was last name updated, and then manually check if an offline device has more recent changes on every attribute instead of overwriting the whole object, but that seems sloppy.
I was also thinking on having an updatedLocally and updatedOnline timestamp property on every Core Data object. This way if the two don't match I can do a diff-check and use the most recent one for conflicts but this still doesn't seem like the cleanest solution. Has anyone else encountered something similar? If so, how did you solve it?
Pseudocode/Summary for what I think? covers every test case but still isn't very elegant/complete:
2 Entities on Parse.com: Contact and Contact History
Contact has first, last, phone, email, onlineUpdate
Contact History has a Primary Key to a Contact to refer to and the same attributes but with history. e.g. first: [{value:"josue",onlineUpdate:"9AM"},{value:"j",onlineUpdate:"10AM"},{value:"JOSUEESP",onlineUpdate:"11AM"}]
1 Entity on Core Data, Contact:
Contact has first, last phone, email, onlineUpdate, and offlineUpdate (IMPORTANT: this is only on Core Data, not on Parse)
for every contact in parse database as onlineContact {
if onlineContact does not exist in core data {
create contact in core data
}
else {
// found matching local object to online object, check for changes
var localContact = core data contact with same UID as onlineContact
if localContact.offlineUpdate more recent than onlineContact.onlineUpdate {
for every attribute in localContact as attribute {
var lastOnlineValueReceived = Parse database Contact History at the time localContact.onlineUpdate for attribute
if lastOnlineValueReceived == localContact.attribute {
// this attribute did not change in the offline update. use latest available online value
localContact.attribute = onlineContact.attribute
}
else{
// this attribute changed during the more recent offline update, update it online
onlineContact.attribute = localContact.attribute
}
}
}
else if onlineContact.onlineUpdate more recent than localContact.offlineUpdate {
// another device updated the contact. use the online contact.
localContact = offlineContact
}
else{
// when a device is connected to the internet, and it saves a contact
// the offline/online update times are the same
// therefore contacts should be equivalent in this else statement
// do nothing
}
}
TL;DR: How are you supposed to structure a kind of version-control system for online/offline updates without accidental overwriting? I'd like to limit bandwidth usage to a minimum.
I would suggest to use key based updates instead of contact based updates.
You should not send the whole contact to the server, in most cases the user would just change a few attributes anyways (things like 'last name' usually don't change very often). This also reduces bandwith usage.
Along with the applied changes of your offline contact you send the
old version number/last update timestamp of your local contact to the server. The server can now
determine whether or not your local data is up to date, simply by looking at your old version number. If your old version number matches the current version number of the server there is no need for your client to update any other information. If this is not the case the server should send you the new contact (after applying your requested update).
You can also save those commits, this would result in a contact history
which does not store the whole contact each time a key was changed but only the changes themselves.
A simple implementation in pseudo code could look like this:
for( each currentContact in offlineContacts ) do
{
if( localChanges.length > 0){ // updates to be made
commitAllChanges();
answer = getServerAnswer();
if(answer.containsContact() == true){
// server sent us a contact as answer so
// we should overwrite the contact
currentContact = answer.contact;
} else {
// the server does not want us to overwrite the contact, so we are up to date!
}
// ...
}
} // end of iterating over contacts
The server side would look just as simple:
for (currentContactToUpdate in contactsToUpdate) do
{
sendBackContact = false; // only send back the updated contact if the client missed updates
for( each currentUpdate in incomingUpdates ) do {
oldClientVersion = currentUpdate.oldversion;
oldServerVersion = currentContact.getVersion();
if( oldClientVersion != oldServerVersion ){
sendBackContact = true;
// the client missed some updates from other devices
// because he tries to update an old version
}
currentContactToUpdate.apply(currentUpdate);
}
if(sendBackContact == true){
sendBack(currentUpdate);
}
}
To get a better understanding of the workflow I will provide an example:
8 AM both clients and the server are up to date, each device is online
Each device has an entry (in this case a row) for the contact 'Foo Bar' which has the primary key ID.
The version is the same for each entry, so all of them are up to date.
_ Server iPhone iPad
ID 42 42 42
Ver 1 1 1
First Foo Foo Foo
Last Bar Bar Bar
Mail f#b f#b f#b
(excuse this terrible format, SO sadly does not support any sort of tables...)
9 AM your iPhone is offline. You notice Foo Bar's email changed to 'foo#b'.
You change the contact information on your phone like this:
UPDATE 42 FROM 1 TO 2 Mail=foo#b
// ^ID ^old version ^new version ^changed attribute(s)
so now the contact in your phone would look like this:
_ iPhone
ID 42
Ver 2
First Foo
Last Bar
Mail foo#b
10 AM your iPad is offline. You notice 'Foo Bar' is actually written as 'Voo Bar'! You apply the changes immediatly on your iPad.
UPDATE 42 FROM 1 TO 2 First=Voo
Notice that the iPad still thinks the current version of contact 42 is 1. Neither the server nor the iPad did notice how you changed the mail address and increased the version number, since no devices were connected to the network. Those changes are only locally stored and visible on your iPad.
11 AM you connect your iPad to the network. The iPad sends the recent update
to the server. Before:
_ Server iPad
ID 42 42
Ver 1 2
First Foo Voo
Last Bar Bar
Mail f#b f#b
iPad -> Server:
UPDATE 42 FROM 1 TO 2 First=Voo
The server can now see that you are updating Version 1 of contact 42. Since version 1 is the current version your client is up to date (no changes commited in the mean time while you were offline).
Server -> iPad
UPDATED 42 FROM 1 TO 2 - OK
After:
_ Server iPad
ID 42 42
Ver 2 2
First Voo Voo
Last Bar Bar
Mail f#b f#b
12 AM you disconnected your iPad from the network and connect your iPhone.
The iPhone tries to commit the recent changes. Before:
_ Server iPhone
ID 42 42
Ver 2 2
First Voo Voo
Last Bar Bar
Mail f#b foo#b
iPhone -> Server
UPDATE 42 FROM 1 TO 2 Mail=foo#b
The server notices how you try to update an old version of the same contact.
He will apply your update since it is more recent than the iPad's update but
will send you the new contact data to make sure you get the updated first name aswell.After:
_ Server iPhone
ID 42 42
Ver 2 2
First Voo Voo
Last Bar Bar
Mail foo#b foo#b
Server -> iPad
UPDATED 42 FROM 1 TO 3 - Ver=2;First=Voo;.... // send the whole contact
/* Note how the version number was changed to 3, and not to 2, as requested.
* If the new version number was (still) 2 the iPad would miss the update
*/
The next time your iPad connects to the network and has no changes to commit it should just send the current version of the contact and see whether it is still up to date.
Now you have committed two offline changes without overwriting each other.
You can easily extend this approach and so some optimizations. For example:
If the client tries to update an old version of the contact, don't send them the whole contact as answer. Rather send them the commits they missed and let them update their contact by themselves. This is useful if you store lots of information about your client and expect few changes to be done between updates.
If the client updated all information about a contact we can assume he does not need to know about the missed updates, however we would let him know about everything he missed (but it would/should have no effect to him)
I hope this helps.
I know nothing about iOs, core data and parse.com, so I can suggest only a general algorithmic solution. I think you can an approach similar to what is done in version control systems.
The simplest thing is to keep all the history on the server: keep all the revisions of the contact list. Now during the synchronization the phone sends information about the last server revision it has seen, and this revision will be the "common parent" for both the current phone revision and current server revision.
Now you can see what has changed on server and on phone since that revision, and apply the usual 3-way comparison: if some field has changed only on the server, then send the new field to the phone; if some field has changed only on the phone, then change it on server too, if some field has been changed both on phone and on server and the changes are different, then you have a conflict and have to ask user.
A variation of this approach might be to work with changes, not revisions. The primary data at both the server and the client will be not the contact list, but a history of its changes. (The current contact list, as well as a set of 'keyframes' can also be kept if needed; it will not be used for conflict resolving algorithm, but can be used so that it can be quickly shown and used.)
Then, when a user synchronizes the data, you download/upload only the changes. If there are any conflict changes, you have nothing left but to ask a user, otherwise you just merge them. How you define a change and which changes are considered conflicting, is up to you. A simple approach can be defining a change as a pair (field, new-value), and two change are conflicting if they have the same field. You can also employ a more advanced conflict resolving logic such as if one change changes only the first half of the email, and the other the second half, then you can merge them.
The correct way to do this is to keep a transaction log. Whenever you save in Core Data you create a log entry in your transaction log. When you are next online you play back the transaction log against the server.
This is how iCloud and other sync services work.
Instead of having separate flag for each of the core data objects, you can have separate table which will store IDs(primary key from database table which stores contact information) of all updated contacts.
Later when user comes online you just fetch those contacts from your actual contact detail table and upload them on your server.
Related
I created a session, shared it to another player and now I want to start a game.
I can see a session with two players on both devices. So, it looks like we're ready to game but I need to change connected status before the game and I can do this on both devices.
But... when I do this on device A, I see that user A is connected and user B isn't. And after that, when I repeat the process on device B, I see vice versa situation. B is connected and A is not.
Here is my code that connect player and send the data:
session.setConnectionState(.connected) { (error) in
if let err = error {
assertionFailure(err.localizedDescription)
}
else {
print("NC:",session.players(with: .notConnected))
print(" C:",session.players(with: .connected))
let m = MoveTransfer(move:1) // test struct to send/receive data
session.send(m.data(), with: .reliable) { (error) in
if let err = error {
assertionFailure(err.localizedDescription)
}
}
}
}
I'm getting error:
The requested operation could not be completed because there are no recipients connected to the session
By the way, I'm unable to change connected state on the simulator (iCloud is logged in).
I forgot to mention, that I'm working on a turn based game.
Edit
Tried again and now after several iterations I got this:
I have both players connected to session. But send data still doesn't work.
here is console output:
NC: [] // not connected array and connected array below
C: [<GKCloudPlayer: 0x17402e700>, id: playerID1, name: Player1,<GKCloudPlayer: 0x17402e900>, id: playerID2, name: Player2]
fatal error: The requested operation could not be completed because there are no recipients connected to the session.
Got this on two real devices.
I was able to send data and receive it on the other device. I used loadSessions function to load all session (I think that loadSession by id would do the trick too).
I did the following, D1 is a device 1 and D2 device 2:
1. D1: load all sessions and set player state to connected
2. D2: load all sessions and set player state to connected
3. D1: load all sessions again and set player state to connected
4. D1 || D2: send data
5. D2 || D1: data 256 bytes from player: <GKCloudPlayer: 0x1c022b380>, id: playerID, name: (null)
Although, I wasn't able to transfer data back and forth on both devices since if we'll add step 6. that sends data from device that just received it, we'll get an error: The requested operation could not be completed because there are no recipients connected to the session.
I do not sure what is the reason of it but I stop my efforts on this stage, since I think now, that I don't need to be connected to session to play turn based game.
I found this "new" iOS 10 APIs abandoned. By Apple and by devs consequently. If you one of those who still trying to use it drop me a note at my twitter (link in my bio) if you want to discuss GKGameSession and related topics.
I have a MVC web database application where the records are basically documents with items.
Documents are locked, not items and they locked by code when the user looks in any of 4 or 5 different screens for any given document.
there is a 10 minute time out on the record locks. The user does not do anything with the record for 10 minutes and another can take the record. There is code that detects the lock was lost and taken by someone else. It works fine and is technically sound.
The workflow of the application relies on the lock being released when the user leaves the screen or closes the browser, or if they press the refresh button.
These are work fine on windows and android but not on ipad.
I understand there is no
beforeunload
on ios but I though there was
unload
or
pageHide
neither of these work.
Here is my code.
var isOnIOS = navigator.userAgent.match(/iPad/i)||
navigator.userAgent.match(/iPhone/i); var eventName = isOnIOS ?
"pageHide" : "beforeunload";
window.addEventListener(eventName, function (event) {
ReleaseRecordLock(); } );
This code works on all mentioned platforms except that the events don't fire on IOS.
It looks to me that this is deliberate on Apple's part so I an not thinking it will change.
So now the question.
What can I do to ensure that these records get unlocked if a user changes screens or closes the browser. If they don't no users will be able to access the document for 10 minutes which will not be acceptable.
Thanks
Edit... I don't need pop ups or notification. I just need reliable unlocking
As mentioned above none of the events that are supposed to work actually fire. pageHide and unload do nothing.
I found mentions of how to get around this problem but no details so I though I would detail it here.
This solutions works with areas and standard sites.
My solution to get around part of this was to detect if the browser is running on IOS and if so to change the link in the menu.
<li>
#{
if(Request.UserAgent.Contains("iPad") || Request.UserAgent.Contains("iPhone"))
{
<a onclick="IOSReleaseLock('controller', 'action')" href="javascript:void(0);">LinkText</a>
}
else
{
#Html.ActionLink("link Text","action","controller",new { Area = "Tasks" },null);
}
}
</li>
Every single link in the application has to have a function called IOSReleaseLock() available or the solution will not work. Not all pages lock records, only those that actually change documents. Reports, and basic website functions such as change password, log out, and the sys admin stuff do not need record locks.
At this point I have 2 versions of IOSReleaseLock()
This is the version that is used on pages that do not required unlocking.
function IOSReleaseLock(_controller, _action)
{
var url = '/__controller__/__action__/';
url = url.replace('__controller__', _controller);
url = url.replace('__action__', _action);
window.location.href = url;
}
This is the version that is placed on pages that required unlocking.
function IOSReleaseLock(_controller, _action )
{
var url = '/__controller__/__action__/';
url = url.replace('__controller__', _controller);
url = url.replace('__action__', _action);
UnloadingRecordLockRelease();
window.location.href = url;
}
Every link has a wrapper so every single page must load a version of IOSReleaseLock(). This includes your /home/index or where ever your application starts. If you miss one then once you are on that page your menu system links will not work anymore.
Pages that require the UnloadingRecordLockRelease() function load that version and the pages that do not require unlocking load the first version.
On IOS every time you click a link, IOSReleaseLock() is called. This may seem to be obvious, but for clarity, the version of IOSReleaseLock() that executes is the version that is on the current page, not the version on the page you are going to.
So as long as the user stays on the site and does not close the browser then the records are unlocked correctly.
When the user logs out all records are unlocked but I have no solution for when the browser tab is closed or when the browser is closed without the user logging out.
When using Firebase iOS, is there a limit on the number of nodes/children/data returned when observing an event type EventTypeValue ?
[[self.firebase appendPathComponent:path] observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
}];
Firebase will "return" all child nodes, unless you explicitly limit the number of nodes with queryLimitedToFirst: or queryLimitedToLast:. See the section of the Firebase documentation on queries for some good examples of these.
One thing to constantly keep in mind when working with Firebase is that you're not just querying the data source, you're actively synchronizing, listening for changes as they happen. Say for example that you have a Firebase that contains status updates from you and your friends. And you have a page that shows the latest 10 updates.
Set up a query ordered by timestamp (a field in your status updates) with queryOrderedByChild.
Limit the query to latest 10 updates with queryLimitedToLast:.
You will receive 10 FEventTypeChildAdded events (assuming that there are at least that many status updates).
A friend posts a new status update.
Your page will receive a FEventTypeChildRemoved for the oldest status update and a FEventTypeChildAdded for the new status update.
I am developing integration with Simperium, the integration is complete and has been running on test machines for sometime, I am starting to get this error on one of the devices and it keeps repeating constantly any ideas?
MeetingPad[891:1103] Simperium error (ActionLinks82), received an invalid change for (a18852011efe4964a6fdeb1853c790f3)
2013-02-07 10:07:05:277 MeetingPad[891:1103] Simperium client ios-7f43b434754d882923e966df5d885755 received change (ActionLinks82) ios-4176925448fa8ae0a2f1d0937627aa6b: {
ccids = (
3f3b4550b23147d49e194038feea09a6
);
clientid = "ios-4176925448fa8ae0a2f1d0937627aa6b";
cv = 5112df4b37a401031dcc5be1;
ev = 2;
id = 9ca0b7ad04314ab9888d75691be784b5;
o = "-";
}
If this occured on a user account what would be the guidance?
One thing to check is that you're using the latest version of the code. The repository was recently open sourced on GitHub. There used to be a bug related to nil values that could cause an invalid diff to appear in your change stream, but it should be fixed now.
Assuming you're using the latest code though, does the error repeat continuously for the same "id" value, or are there different values?
Looking at the Simperium code where this error occurs, it's possible it could be displayed if you've deleted an object locally and remotely at around the same time. In your app, might ActionLinks fit that pattern, i.e. are you creating and deleting a lot of them across multiple clients?
If that is indeed the cause, then the error is innocuous and we should patch the code. Let me know what you discover.
FATAL ERROR: CALL_AND_RETRY_2 Allocation Failed - process out of memory
I'm seeing this error and not quite sure where it's coming from. The project I'm working on has this basic workflow:
Receive XML post from another source
Parse the XML using xml2js
Extract the required information from the newly created JSON object and create a new object.
Send that object to connected clients (using socket.io)
Node Modules in use are:
xml2js
socket.io
choreographer
mysql
When I receive an XML packet the first thing I do is write it to a log.txt file in the event that something needs to be reviewed later. I first fs.readFile to get the current contents, then write the new contents + the old. The log.txt file was probably around 2400KB around last crash, but upon restarting the server it's working fine again so I don't believe this to be the issue.
I don't see a packet in the log right before the crash happened, so I'm not sure what's causing the crash... No new clients connected, no messages were being sent... nothing was being parsed.
Edit
Seeing as node is running constantly should I be using delete <object> after every object I'm using serves its purpose, such as var now = new Date() which I use to compare to things that happen in the past. Or, result object from step 3 after I've passed it to the callback?
Edit 2
I am keeping a master object in the event that a new client connects, they need to see past messages, objects are deleted though, they don't stay for the life of the server, just until their completed on client side. Currently, I'm doing something like this
function parsingFunction(callback) {
//Construct Object
callback(theConstructedObject);
}
parsingFunction(function (data) {
masterObject[someIdentifier] = data;
});
Edit 3
As another step for troubleshooting I dumped the process.memoryUsage().heapUsed right before the parser starts at the parser.on('end', function() {..}); and parsed several xml packets. The highest heap used was around 10-12 MB throughout the test, although during normal conditions the program rests at about 4-5 MB. I don't think this is particularly a deal breaker, but may help in finding the issue.
Perhaps you are accidentally closing on objects recursively. A crazy example:
function f() {
var shouldBeDeleted = function(x) { return x }
return function g() { return shouldBeDeleted(shouldBeDeleted) }
}
To find what is happening fire up node-inspector and set a break point just before the suspected out of memory error. Then click on "Closure" (below Scope Variables near the right border). Perhaps if you click around something will click and you realize what happens.