1

I am creating an iOS app that uses swiftUI for the app but it talks to a Rails Backend via HTTP requests to JSON. I would like to be able to send push notifications from the backend to users of the frontend.

I gather this deviceToken on the frontend like so:

class AppDelegate: NSObject, UIApplicationDelegate {

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
        print("deviceToken", deviceTokenString)
    }
}

Which gives me a deviceTokenString that looks something like:

token = "9cfa2410a3f8326529db2e6e34dbcd3cc6664c7ee3675a08a34bd42429892068"

I got this from this blog post which references this stack-overflow question.

I then take that token over to my Rails code which looks like this (I'm trying to use Apnotic but maybe I should be using something else)

module PushNotifier

  class << self

    def push(token)
      notification = Apnotic::Notification.new(token)
      notification.alert = 'Test notification from rails'
      notification.topic = 'me.MyApp'
      response = connection.push(notification)
      puts response
    end 

    def connection
      Apnotic::Connection.new(
        auth_method: :token,
        cert_path: "config/keys/AuthKey.p8",
        key_id: Rails.application.credentials.apple.p8_key_id,
        team_id: Rails.application.credentials.apple.team_id
      )   
    end 
  end 
end

but I am getting this:

#<Apnotic::Response:0x00000001069e1018 @headers={":status"=>"400", "apns-id"=>"272ebadf-9b2f-47f6-8ae0-5746422e7213"}, @body="{\"reason\":\"BadDeviceToken\"}">

so a 400 with BadDeviceToken

I'm not sure if the frontend is providing a bad token or somehow the backend is mangling it.

It could be that my topic is wrong?

Could it be that the token I am providing is not in the correct hex format of the deviceToken string from the frontend?

I think my p8 key and my credentials and certificates are all handled correctly.

Any advice about what could be going on?

goddamnyouryan
  • 6,854
  • 15
  • 56
  • 105

1 Answers1

-1

Ok I figured it out. I thought maybe I should post here.

This stack overflow answer gave me the idea:

What are the possible reasons to get APNs responses BadDeviceToken or Unregistered?

I realized that maybe my rails side was trying to send to the "production" server when I should be doing development, at least at the moment. I poked around the Apnotic docs and boom:

I changed this line:

Apnotic::Connection.new(

to

Apnotic::Connection.development(

which I don't like that API design, but it fixed the issue.

goddamnyouryan
  • 6,854
  • 15
  • 56
  • 105