lib/apn/notification.rb in apn_sender-1.0.6 vs lib/apn/notification.rb in apn_sender-2.0.0
- old
+ new
@@ -20,16 +20,19 @@
class Notification
# Available to help clients determine before they create the notification if their message will be too large.
# Each iPhone Notification payload must be 256 or fewer characters. Encoding a null message has a 57
# character overhead, so there are 199 characters available for the alert string.
MAX_ALERT_LENGTH = 199
+ DATA_MAX_BYTES = 256
attr_accessor :options, :token
def initialize(token, opts)
@options = opts.is_a?(Hash) ? opts.symbolize_keys : {:alert => opts}
@token = token
+ truncate_alert! if APN.truncate_alert
+
raise "The maximum size allowed for a notification payload is 256 bytes." if packaged_notification.size.to_i > 256
end
def to_s
packaged_notification
@@ -39,12 +42,10 @@
def valid?
return true if [:alert, :badge, :sound].any?{|key| options.keys.include?(key) }
false
end
- protected
-
# Completed encoded notification, ready to send down the wire to Apple
def packaged_notification
pt = packaged_token
pm = packaged_message
[0, 0, 32, pt, 0, pm.size, pm].pack("ccca*cca*")
@@ -71,7 +72,17 @@
end
hsh.merge!(opts)
ActiveSupport::JSON::encode(hsh)
end
+ def truncate_alert!
+ while packaged_notification.size.to_i > DATA_MAX_BYTES
+ if @options[:alert].is_a? Hash
+ last = @options[:alert]['loc-args'].pop
+ @options[:alert]['loc-args'] << last[0..-2]
+ else
+ @options[:alert] = @options[:alert][0..-2]
+ end
+ end
+ end
end
end