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.