Rutger Huijsmans Rutger Huijsmans - 1 year ago 90
Swift Question

Registering for Push notifications functions don't get called

I'm making this sweet app that requires Push notifications.

However when trying to grab the Push token not all required functions seem to get executed.

The user does get presented with this Alert:

enter image description here

When the user hits OK I step through my code and see that not everything gets executed:

override func viewDidLoad(){
let tapper = UITapGestureRecognizer(target: view, action:#selector(UIView.endEditing))
tapper.cancelsTouchesInView = false

print("gets called")

func registerForPushNotifications(application: UIApplication) {
print("gets called")
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print("doesn't get called")
if notificationSettings.types != .None {

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("doesn't get called")
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var apnsTokenString = ""

for i in 0..<deviceToken.length {
apnsTokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])

Constant.pushToken = apnsTokenString

print("Device Token:", Constant.pushToken)

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
debugPrint("Error Registering Remote Notification")

In my console the following gets printed:

gets called

gets called

Meaning that not all required functions get called. What am I doing wrong?

Answer Source

Assuming all of the code you posted in your question is in your view controller class, the problem is that you need to put the UIApplicationDelegate methods in your actual app delegate class, not the view controller class. Simply move those methods to the proper class and they will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download