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.
}