POST data from iOS to php server always NULL - iOS

2019-04-14 08:25发布

问题:

i am implementing a FCM app server and wanted to store the device registration token id into my own database (Server written in PHP).

I realise the data in device id token is always null, Can someone point the right way to store the token accordingly into database?

Really appreciated perhaps someone could guide me on this issue, thanks!

Kindly refer the code/screenshots below:-

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)
    Callquery(token)

}

AppDelegate.swift (Callquery method which send a POST request to server side script)

func Callquery(_ token: String)
{

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

    // create the request
    var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php")!)

    // 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("There was error during datatask session")
            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
                    print("There is an error during parse JSON datatask")
                    return
                } else {
                    // show confirmation
                    print("datatask with JSON format performed successfully")
                }
            }
        }
        print(request)
    }).resume()
}

Service Side Script(registerToken.php):

<?php
include 'config.php';

$token = $_POST['token'];

$sql = "INSERT INTO users (email,device_id) VALUES ('email','$token')";

mysqli_query($conn, $sql);



mysqli_close($conn);
?>

Running App with real devices log as below:-

Database users table (device id always has nothing):-

users table structure:-

tokenString :-

回答1:

I had solved this issue by using GET method instead of POST method as below:-

Appdelegate.swift :

var request = URLRequest(url: URL(string:"https://YourURL.com/admin/registerToken.php?token=\(token)")!)

Server side script :

$token = $_GET['token'];