How do I constantly check if something on a server (Parse) has changed without thousands of requests? - swift

I am creating an application which has a follow mechanism where the followed user has to accept the request of a following (similar to private accounts on instagram).
I then want the following user to find out when the other user has checked a million times (every time the following user opens the screen if I did the query in viewDidLoad). However, the problem with this, is that there will be a lot requests which will expensive to me as I will have to pay for the requests to Parse so I want to minimise these queries.
Currently, the best thing I can think of is to check once a day at midnight for example but this doesn't seem very seamless.
Is there a better way of doing this?

For starters consider how stale you are willing to allow an app's view of the world to be and cache the response that long. If a user views that screen every 30 seconds you might only want to actually check with the server 5 minutes after the last successful response (or the last response which had 0 follow requests).
You might consider switching from this sort of "pull" polling where the client decides when to ask the server if anything has changed to a "push" model where the server can inform the client when a change occurs. For example you can send a silent background push notification to a user's devices when they have a follow request, the app can then respond by performing your existing query.
You might still want polling or user triggered requests (like a "pull to refresh" gesture) as a fallback for missed notifications or devices with notifications disabled but you should be able to drastically reduce request volume.

Related

What to do if a RESTful api is only partly successful

In our design we have something of a paradox. We have a database of projects. Each project has a status. We have a REST api to change a project from “Ready” status to “Cleanup” status. Two things must happen.
update the status in the database
send out an email to the approvers
Currently RESTful api does 1, and if that is successful, do 2.
But sometimes the email fails to send. But since (1) is already committed, it is not possible to rollback.
I don't want to send the email prior to commit, because I want to make sure the commit is successful before sending the email.
I thought about undoing step 1, but that is very hard. The status change involves adding new records to the history table, so I need to delete them. And if another person make other changes concurrently, the undo might get messed up.
So what can I do? If (2) fails, should I return “200 OK” to the client?
Seems like the best option is to return “500 Server Error” with error message that says “The project status was changed. However, sending the email to the approvers failed. Please take appropriate action.”
Perhaps I should not try to do 1 + 2 in a single operation? But that just puts the burden on the client, which is worse!
Just some random thoughts:
You can have a notification sent status flag along with a datetime of submission. When an email is successful then it flips, if not then it stays. When changes are submitted then your code iterates through ALL unsent notifications and tries to send. No idea what backend db you are suing but I believe many have the functionality to send emails as well. You could have a scheduled Job (SQL Server Agent for MSSQL) that runs hourly and tries to send if the datetime of the submission is lapsed a certain amount or starts setting off alarms if it fails as well.
If ti is that insanely important then maybe you could integrate a third party service such as sendgrid to run as a backup sending mech. That of course would be more $$ though...
Traditionally I've always separated functions like this into a backend worker process that handles this kind of administrative tasking stuff across many different applications. Some notifications get sent out every morning. Some get sent out every 15 minutes. Some are weekly summaries. If I run into a crash and burn then I light up the event log and we are (lucky/unlucky) enough to have server monitoring tools that alert us on specified application events.

How to handle multiple push notifications with user data arrived at different times?

My app is receiving APNs sent from server to Apple backend. Naturally a user may not open the app once a notification arrives to user's device. In meantime my server may push more notifications. They all contain some user data that is important when a notification is processed. So how to deal with it? iOS won't bundle and give me a batch, will it?
Here are ways how I am going to tackle it, none of which is simple.
Server keeps track of not seen data and upon arriving a new request always sends a batch of all new notifications, reflecting the count as badge count.
Client is opened by taping on notification popup. In this case it has all needed data in didReceiveRemoteNotification.
OR
Client ignores notification popup and opens app (possibly later) by tapping on app icon. In this case didReceiveRemoteNotification is not called and thus app has to fetch all needed data from server.
OR
Server never sends any user data and client always checks for new stuff every time it starts or fetches data in didReceiveRemoteNotification.
Anything else? Something simpler I am missing?
Number 4 is the right approach. There is no guarantee that any of your app code will run when an APN is received, except on iOS7. So when your app starts, it has to check with your servers for any new information that it should display.
It's simplest to code this to alway ask your servers for the latest information to display, rather than rely on the information in the APN. Use the information in the APN only to determine which new information to navigate to, so that the app displays whatever the user tapped on.
This has changed with iOS7, where you can use the remote-notification background mode to be launched whenever a push message arrives. See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveRemoteNotification:fetchCompletionHandler:

Real time App with Facebook

Does Facebook provide access to any real time APIs so that you can respond to events as soon as they happen? If not, what alternatives are there and what are their limitations? For example, if I use polling instead, will they limit my api calls? And if I try using RSS feeds, about how much delay can I expect? Or maybe it would be possible to receive and process email notifications (if I could convince a user to forward mail to another email address), as they seem to be dispatched pretty promptly.
I've never tried polling user data, but I think it will work without issues. As far as I know there are no restrictions on the number of API calls you can make on facebook.
As far as the Queries are concerned, what I have seen and I think this is how they implement it. If your query asks for too much data(takes too much time to process is how they measure this I think) - the query will just fail.
eg: I had this app that would pull all the status messages of all the friends of the user and display it in one place. I first queried for all the friends of the user - this worked okay. But at the same time if I ran a loop to get all the status messages for each friend - it would just fail.
I think you can call individual queries without issues, just be careful you query only data you need, cause, if the queries are too big or too many they will just fail. Best way to findout is running tests yourself.
The Facebook Graph API will allow you to subscribe to real time changes. You can currently only subscribe to users, permissions and errors, but they promise to allow subscribing to more objects in the future.

How to track user online status?

I would like to capture the following parameters:
lastAccessedTime - The time when the user visited the site the last time (usually shown during the login process)
isOnline - A boolean to represent if a user is online or not.
a. Would it make sense to have these variables as part of the User table itself or should this be handled via a separate user audit table?
b. If certain SOAP / REST API's expose the functionality via API calls, how do you track the above parameters (e.g. Would you modify the lastAccessedTime in such cases - this might confuse the user if he logs into the portal, isOnline bit also will not make sense if the user does API calls).
I would create a session table that links back to the user. Instead of an isOnline field, I would just run a query for sessions that have been active within the last x amount of time. I would also update that session field with each request, even if that request is coming through an API.
This does create some overhead in pruning the session table, but you also don't clutter up your user table with non-user information, which can't be pruned.
Make the lastTimeActive a field in the user table, and update it with each page access. Your "Users Online" list is all users whose lastTimeActive is within 5 minutes.
I would create another table (userid, lastTimeActive), and frequently update & check the table.
// update
update onlineusers set lastTimeActive = getdate() where userid=1234
// check
delete from onlineusers where lastTimeActive < dateadd(minute,-5,getdate())
The biggest problem with tracking user presence (onine/offline) over HTTP is how to determine when the user has gone offline.
It's easy to determine when the user has come online - the mere presence of an authenticated request assumes that the user is active. However, since HTTP is stateless, the lack of a subsequent request can mean either that the user is gone offline, or that the user is online, but just hasn't done anything specific with your app recently.
Thus the best guess you can make is to have a timeout and if the user has not made a request during that timeout, to switch to offline state.
The simplest implementation would be to have a lastTimeActive, as Jonathan Sampson suggested. However, this won't give you the length of the user session, only an approximation of who's online at this moment.
More complex approach would be to have lastTimeActive and lastTimeLoggedIn. LastTimeLoggedIn is set at the time of first auth request that is more than 5 minutes from a previous auth request. A user is considered online, if there was an authenticated request in the last five minutes. The session length for the user is the time difference between lastTimeActive and lastTimeLoggedIn.
If your app also offers the choice of logging out to the user, you chouls consider that action also as going offline. However, unless your app is a banking app, chances are the users will just close their browser.
Also, avoid any background threads for updating the offline/online status of your users. You should be running the logic above only when there's an explicit request about the status of particular user and you should be updating only the users you were asked for.

how to send a http post request to server in iphone app?

how do i send device token from my native iphone app with a specific timer request so that after the specified time push notification alert comes to device.
The title of your question and the text of it don't exactly match.
The easiest way to set up a timer request for push is to sign up with a push service provider that offers timed requests (UrbanAirship does but you may also want to check others like iLime or push.io).
The other option is to write a server where you can queue the requests then run a cron job to push them out. Obviously, that'll take more work. To actually post the message, you could use something like ASIHTTPRequest.
You may also want to tell your users not to rely on exact timing. A lot of variables enter into the process especially if user is on WiFi.