def write(self, notifications):
    "Connect to the APNS service and send notifications"
    if not self.factory:
      log.msg('APNSService write (connecting)')
      server, port = ((APNS_SERVER_SANDBOX_HOSTNAME 
                      if self.environment == 'sandbox'
                      else APNS_SERVER_HOSTNAME), APNS_SERVER_PORT)
      self.factory = self.clientProtocolFactory()
      context = self.getContextFactory()
      reactor.connectSSL(server, port, self.factory, context)
    
    client = self.factory.clientProtocol
    if client:
      return client.sendMessage(notifications)
    else:      
      d = self.factory.deferred
      timeout = reactor.callLater(self.timeout, 
        lambda: d.called or d.errback(
          Exception('Notification timed out after %i seconds' % self.timeout)))
      def cancel_timeout(r):
        try: timeout.cancel()
        except: pass
        return r
      
      d.addCallback(lambda p: p.sendMessage(notifications))
      d.addErrback(log_errback('apns-service-write'))
      d.addBoth(cancel_timeout)
      return d
Connect to the APNS service and send notifications