grocer/grocer — pull request #29 by Kikimora (2012-12-24 19:25:09+00:00)
Title: Possible fix for #14 Socket connection drops next notification if invalid notification is sent

Hi, I got the same problem as described in issue #14. Later on I discovered than "invalid" device tokens which trigger the problem came from Debug versions of my app. Basically Apple drops connection and does not send anything as soon as it sees token from sandbox environment send to production one. Once I removed sandbox tokens my pushes sent fine.

But this is only part of the picture. I dig a bit deeper and implemented simple error checking as described in apple docs. You can see this code in the pull request. I used IO.select trick from "Lead Zeppeling" to get error messages. And weird thing happened. Once I read errors I see that Apple correctly reports sandbox tokens as being invalid (error code 8). But Apple reports it only once! Next pushes with same tokens (including invalid once) work without connection drops and without any errors from Apple side. I do not know who to blame this for. Maybe IO.select did the trick, maybe reading error information from socket, maybe anything else...

Anyway this pull request has the code I created to read errors. And using it I was able to fix the problem.

My sending code looks like this
```ruby
devices.each_with_index do |device, index|
n = Grocer::Notification.new(device_token:device.token,
alert: news_content.title,
identifier: index)
pusher.push(n)
Rails.logger.debug "Pushing #{device.token} #{news_content.title}"
end
errors = pusher.read_errors
invalid_devices = errors.map {|error| devices[error[:identifier]]}
Rails.logger.warn "APNS send resulted in errors: #{errors}"
devices.delete_all({:id.in => invalid_devices})
```