0

After reading several different tutorials I am struggling to figure out why my POST isn't working.

Swift:

func request(endpoint: String,
                 loginData: Login,
                 completion: @escaping (Result<User, Error>) -> Void) {
        guard let url = URL(string: baseURL + endpoint) else {
            completion(.failure(NetworkingError.badURL))
            return
        }

        var request = URLRequest(url: url)

        do {
            let loginData = try JSONEncoder().encode(loginData)

            request.httpBody = loginData

            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        } catch {
            completion(.failure(NetworkingError.badURL))
        }

        handleResponse(for: request, completion: completion)
    }

    func handleResponse(for request: URLRequest,
                        completion: @escaping (Result<User, Error>) -> Void) {
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in
            DispatchQueue.main.async {
                guard let unwrappedResponse = response as? HTTPURLResponse else {
                    completion(.failure(NetworkingError.badResponse))
                    return
                }

                print(unwrappedResponse.statusCode)

                switch unwrappedResponse.statusCode {
                case 200 ..< 300:
                    print("Success")
                default:
                    print("Failure")
                }

                if let unwrappedError = error {
                    completion(.failure(unwrappedError))
                }

                print("Data reponse:", data!)
                if let unwrappedData = data {
                    print("unwrappedData", unwrappedData)
                    do {
                        let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
                        print("JSON", json)

                        if let user = try? JSONDecoder().decode(User.self, from: unwrappedData) {
                            completion(.success(user))
                        } else {
                            let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
                            completion(.failure(errorResponse))
                        }
                    } catch {
                        print("Data Failure")
                        completion(.failure(error))
                    }
                }
            }
        }
        task.resume()
    }

PHP:

<?php
    include 'Connection.php';

    $uemail = $_POST['email'];
    $upassword = $_POST['password'];

    $testtext = "This is a test";
    $openFile = fopen("testfile.txt", "w") or die("Unable to open file!");
    fwrite($openFile, $testtext);
    fwrite($openFile, $uemail);
    $newLine = "\n";
    fwrite($openFile, $newLine);
    fwrite($openFile, $upassword);

    // Close the Database
    $conn->close();
?>

So I was posting everything into a text file to see if it all worked. When it all executes the only line in the .txt file is "This is a test". Right after I created the loginData constant I ended up decoding the JSON that I created and got the results:

Test Decode:  {
    email = asd;
    password = qwe;
}

What am I missing or doing wrong? Any guidance would be helpful. I did get this from a tutorial. The only thing the tutorial didn't show was the actual API. I just wanted to get this to work then I can actually modify to my needs, and put it into my own.

Micheal
  • 309
  • 4
  • 16
  • You have just created a request but it is not executed at all. You can check [this](https://stackoverflow.com/a/24016254/2395636) and other answers to make it work. – Kamran Oct 06 '19 at 06:16
  • Ok, I have updated my answer. I did leave some code out because I thought the error was within this part. – Micheal Oct 06 '19 at 07:04
  • 1
    You are sending parameter in a JSON format, but your PHP code is not for JSON. Update your PHP code to receive JSON. Or else update your Swift code to send the right request for `$_POST`. – OOPer Oct 06 '19 at 09:30
  • @OOPer thank you for the guidance. After some research and some test and trial I finally got it to work. Now on to the next task to solve. – Micheal Oct 06 '19 at 11:05
  • Happy to hear that. Please take some time to post your solution as an answer. – OOPer Oct 06 '19 at 11:16

1 Answers1

0

I was passing the data through json. So I had to decode the json. I simply added:

$postdata = json_decode(file_get_contents("php://input"),TRUE);
Micheal
  • 309
  • 4
  • 16