aznelite89 aznelite89 - 1 month ago 21
Swift Question

How to store push notification token into external database - iOS 10, Swift 3

i had implement FCM and i would like to send push notification from my own app server(written in PHP). Therefore, i would need to store the device token for fcm in my Phpmyadmin database. Is there a way to store the token into my database from iOS swift? would be appreciated if someone would give me some tips regarding this issue, thanks!

AppDelegate.swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""

for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
}

print("Registration succeeded!")
print("Token: ", token)

}


Database table structure:

enter image description here

Answer

Step-1

create the common method for access in two places

  func Callquery(_ token: String)   
 {

  // append parameter to oneDictionary
  let tokenString = ["keyName": token] as [String: Any]

   // create the request
  var request = URLRequest(url: URL(string:"yourServer URL")!)

  // set the method as POST
  request.httpMethod = "POST"

  // append the paramter to body
  request.httpBody = try! JSONSerialization.data(withJSONObject: tokenString, options: [])

// create the session
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
    if error != nil {
        print(error)
    } else {
        do {
            guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }

            guard let errors = json?["errors"] as? [[String: Any]] else { return }
                if errors.count > 0 {
                    // show error
                    return
                } else {
                    // show confirmation
                }
            }
        }
    }).resume()
   }

Step-2

after iOS9 we need to enble the transport security in out .plist, see this for example

Step-3

call method in two places

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
  print("Registration failed!")

    Callquery("") // pass the empty paramter if user deny the permission.

   }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)

      Callquery(token) // pass the token paramter if user accept the permission.

}