In PHP, how do you use fread() to check if there is an error response when sending enhanced push notifications?
I have read the Apple docs, a couple vague posts thru Google, and a couple questions/answers here on SO but this was still very confusing.
Here is what I looked at:
http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html
Reading error from Apple enhanced push notification with PHP
iPhone Push Notification – Error response problem
I am going to answer my own question below, based on the fact that: (1) I found this a very confusing topic, and (2) I had to piece the information together with lots of trial and error to get it to work, and (3) this blog post that says it is encouraged: https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
When you send a push notification, there are several problems:
If there is a problem, Apple will disconnect you but you don’t know about it. When you use basic notifications there is no way to know if they were all sent or not. SOLUTION: This is the whole point of using an enhanced notification and then checking for an error response. Note that we will use “ORDER BY id” in database query and then use the id as the identifier that we send in notification. This way, if there is a problem, we know exactly which row in the db caused the problem (and therefore we know when Apple disconnected us and stopped sending the notifications). We can then continue sending Push notifications to all the rows after the row that caused the problem, without having to resend to the ones we already sent to.
Apple does NOT send any response back if everything is ok, so this can cause your script to pause and wait forever while fread() is waiting for data that is not coming. SOLUTION: Need to set stream_set_blocking to 0 so that fread always returns right away. Note that this causes another minor issue that fread can return before it receives an error response, but see the workaround in the code, which is just to pause for 1/2 a second AFTER all your sending is done and then check fread one more time.
You can send multiple push notifications much faster than it takes an error response to get back to you. SOLUTION: Again this is the same workaround mentioned above… pause for 1/2 a second AFTER all your sending is done and then check fread one more time.
Here is my solution using PHP, which addresses all my problems that I encountered. Its pretty basic but gets the job done. I have tested it with sending a few notifications at a time as well as sending out 120,000 at one time.