0

Here is my swift for registering the user:

//Information fields
@IBOutlet weak var user: UITextField!
@IBOutlet weak var pass: UITextField!
@IBOutlet weak var pass2: UITextField!
@IBOutlet weak var name: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var Message: UILabel!


//Register button
@IBAction func register(_ sender: Any) {

    let Parameters = ["username": user.text, "password": pass.text, "email": email.text, "name": name.text]

    let url = URL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")!

    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: Parameters, options: .prettyPrinted)
    } catch let error {
        print(error.localizedDescription)
        Message.text = String(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                }
        } catch let error {
            print(error.localizedDescription)
            self.Message.text = String(error.localizedDescription)
        }
    })
    task.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

Here is the PHP:

<?php
require_once 'DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('username', 'password', 'email', 'name'))) {
    //getting values
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $name = $_POST['name'];

    //creating db operation object
    $db = new DbOperation();

    //adding user to database
    $result = $db->createUser($username, $password, $email, $name);

    //making the response accordingly
    if ($result == USER_CREATED) {
        $response['error'] = false;
        $response['message'] = 'User created successfully';
    } elseif ($result == USER_ALREADY_EXIST) {
        $response['error'] = true;
        $response['message'] = 'User already exist';
    } elseif ($result == USER_NOT_CREATED) {
        $response['error'] = true;
        $response['message'] = 'Some error occurred';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}

//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{

//Looping through all the parameters
foreach ($required_fields as $field) {
    //if any requred parameter is missing
    if (!isset($_POST[$field]) || strlen(trim($_POST[$field])) <= 0) {

        //returning true;
        return true;
    }
}
return false;
}

echo json_encode($response);
?>

Here is the information I am trying to post to the database: iOS Registration Fields:

enter image description here

And the error I am receiving from Xcode when hitting the register button:

2017-11-14 00:42:01.529344-0500 WeissProf4[8754:662299] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-11-14 00:42:01.530670-0500 WeissProf4[8754:662299] [MC] Loaded MobileCoreServices.framework
2017-11-14 00:42:01.550941-0500 WeissProf4[8754:662299] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/leviweiss/Library/Developer/CoreSimulator/Devices/C98EE410-1CA2-4B4B-9ED8-A4F112C629E2/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-11-14 00:42:03.468653-0500 WeissProf4[8754:662299] [MC] Reading from private effective user settings.
2017-11-14 00:42:04.769899-0500 WeissProf4[8754:662505] [MC] Invalidating cache
2017-11-14 00:42:05.281372-0500 WeissProf4[8754:662299] [MC] Reading from private effective user settings.
["message": Required parameters are missing, "error": 1]

I'm not sure what is going on, I know the PHP is successfully connecting to the DB and is able to post the required info (tested with Postman). I am thinking it could be an error with how Swift deals with posting in PHP, although I am absolutely not a PHP expert.

4
  • If it works with Postman, then it's simply your Swift code that doesn't post the params correctly. Try adding a var_dump($_POST) to your PHP code and check what Swift actually posts. Commented Nov 14, 2017 at 5:59
  • Actually, it looks like you're posting a json string in the body instead of using a "normal" www-form (posting data like param1=value1&param2=value2&...). If you post a json string in the body, you need to extract the string and parse it manually in PHP. Check the answer in this question: stackoverflow.com/questions/37400639/… Commented Nov 14, 2017 at 6:04
  • Thank you for point that out, works great! Added an edit for the solution in Swift 4. Commented Nov 14, 2017 at 7:36
  • Add it as an answer instead. That way you can accept it, making others know the issue is resolved and easier for future visitors to find. Commented Nov 14, 2017 at 12:23

1 Answer 1

1

SOLUTION Swift4:

@IBAction func register(_ sender: Any) {

let request = NSMutableURLRequest(url: NSURL(string: "http://cgi.soic.indiana.edu/~lvweiss/prof4/register.php")! as URL)
request.httpMethod = "POST"
let postString = "username=\(user.text!)&password=\(pass.text!)&email=\(email.text!)&name=\(name.text!)"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print("error=\(String(describing: error))")
        return
    }

    print("response = \(String(describing: response))")

    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print("responseString = \(String(describing: responseString))")
}
task.resume()

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.