How to send data from Xcode 8 into PHP MySQL database? - php

I would like to ask on how to post the data from Xcode 8 into PHP MySQL database. Right now I have textField username and register button to triggered the function post.
Here's my code so far.
registerVC.swift
import UIKit
class RegisterVC: UIViewController {
#IBOutlet var usernametxt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func register_click(_ sender: Any) {
if usernametxt.text!.isEmpty{
usernametxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
else{
// Insert data into database
}
}
}
Register.php
<?php
$connect = mysqli_connect("", "", "", "");
global $connect;
if(isset($_POST['username']))
{
$username = $_POST['username'];
$insert = "INSERT INTO table (username)
VALUES ('$username')";
$run = mysqli_query($connect,$insert);
$response = array();
$response["success"] = true;
echo json_encode($response);
}
?>

In your else add sendData(usernametxt.text)
and add below function in your VC file
func sendData(username : String) {
var request = URLRequest(url: URL(string:"http://YOUR_WEBPAGE_ADDRESS")!)
request.httpMethod = "POST"
let postString = "name="+username
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
}
task.resume()

Related

How do I connect my swift ios app to a database, and why is it giving me a status 500 error?

I am creating an simple ios app that asks the user for userid and sends that to a database. This is my first app so i am new to app-database connection. Here is the entire code for the page that asks for the userid and sends that to the a php file.
//
// NextSecondViewController.swift
// DepressionApp1
//
// Created by Ashok Nambisan on 12/2/22.
//
import UIKit
import Foundation
struct ResponseObject<T: Decodable>: Decodable {
let form: T
}
struct Foo: Decodable {
let name: String
}
extension Dictionary {
func percentEncoded() -> Data? {
map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed: CharacterSet = .urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
class NextViewController: UIViewController {
let URL = ""
#IBOutlet var Text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
initializeHideKeyboard()
}
func initializeHideKeyboard(){
//Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(dismissMyKeyboard))
//Add this tap gesture recognizer to the parent view
view.addGestureRecognizer(tap)
}
#objc func dismissMyKeyboard(){
//endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
//In short- Dismiss the active keyboard.
view.endEditing(true)
}
#IBOutlet weak var labelf: UILabel!
#IBOutlet weak var textg: UITextField!
#IBAction func Submit(_ sender: Any) {
//created NSURL
let url = Foundation.URL(string: "http://ashok.local:8888/insert.php")!
//creating NSMutableURLRequest
var request = URLRequest(url: url)
request.httpMethod = "POST"
//setting the method to post
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
//getting values from text fields
print(textg.text)
let parameters: [String: Any] = [
"userid": textg.text
]
request.httpBody = parameters.percentEncoded()
print("URLRequest: \(request)")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data,
let response = response as? HTTPURLResponse,
error == nil
else { // check for fundamental networking error
print("error", error ?? URLError(.badServerResponse))
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return}
do {
let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
print(responseObject)
} catch {
print(error) // parsing error
if let responseString = String(data: data, encoding: .utf8) {
print("responseString = \(responseString)")
} else {
print("unable to parse response as string")
}
}
}
task.resume()
//executing the task
}
#IBAction func previbutton(_ sender: Any) {
let vmc = storyboard?.instantiateViewController(withIdentifier: "second") as! SecondViewController
vmc.modalPresentationStyle = .fullScreen
present(vmc,animated:true)
}
}
Then here is the code for the config.php
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'emotion');
try{
$pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
and insert.php:
<?php
// set up the response array
$response = array();
// check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// get the userid from the POST request
$userid = $_POST['userid'];
// connect to the database
require_once "config.php";
// insert the record into the database
$sql = "INSERT INTO data (userid) VALUES (:userid)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':userid', $userid);
$stmt->execute();
// set the success message in the response array
$response['error'] = false;
$response['message'] = 'Record inserted successfully';
} else {
// set the error message in the response array
$response['error'] = true;
$response['message'] = 'You are not authorized';
}
// return the response as JSON
echo json_encode($response);
// close the database connection
unset($pdo);
When i run the code on xcode, it gives me the status 500 error
I know my php-database connection is fine since when i just sent a number to the database in the userid column, it worked. However, when I connected the swift to the php for userid, it gives me a status 500 error and doesn't work. I don't know where the error is, could someone help me?

Swift save PHP session to stay authenticated

I am building an app, which has login page connected with my AWS server using PHP and MySQL, everything is working fine except that I have no idea how to save the PHP session within the app so the user can stay authenticated.
Part of my PHP code:
<?php
$session_start();
...
...
if($verify){
echo "Verfied";
$_SESSION["Authenticated"] = 1;
} else {
echo "Unverified";
$_SESSION["Authenticated"] = 0;
}
...
...
?>
Part of Swift code:
let url = URL(string: "http://localhost/login.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)!
print("responseString = \(String(describing: responseString))")
DispatchQueue.main.async() {
if (responseString == "Vaild!") {
self.performSegue(withIdentifier: "MainPageSegue", sender: self)
} else {
self.errorLabel.text = "Invalid username or password."
}
}
}
task.resume()
How can I save the session within my app so the user stay authenticated?

swift login POST connection with php

I am new to Swift and I am trying to create secure login with PHP in backend. But somewhere I am going wrong, my viewcontroller is segue to next view controller even though i Don't give login credential and getting following error in console:
Please help !!
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set
my code:
#IBAction func loginAuthentication(sender: UIButton) {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let myUrl = NSURL(string: "my url");
var request = NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod = "POST"// Compose a query string
let postString = "username = \( NameTextField.text!) & password = \( passwortTextField.text!) ";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data , response , error in
if error != nil
{
let alert = UIAlertView()
alert.title = "Login Failed!"
alert.message = "Error: \(error)"
alert.delegate = self
alert.addButtonWithTitle("OK")
alert.show()
return
}
// You can print out response object
print("*****response = \(response)")
let responseString = NSString(data: data! , encoding: NSUTF8StringEncoding )
if ((responseString?.containsString("")) != nil) {
print("incorrect - try again")
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .Alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .Default) { (action) -> Void in
}
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.presentViewController(alert, animated: true, completion: nil)
}
else {
print("correct good")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("toPflegerProfile")
self.presentViewController(controller, animated: true, completion: nil)
}
print("*****response data = \(responseString)")
do {
//create json object from data
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? [String: Any] {
if let email = json["UserName"] as? String,
let password = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
}
} catch let error {
print(error)
}
}
task.resume()
}
php code :
<?php
require_once 'db.php';
$conn = connect();
if($conn)
{
if (isset($_GET['loginuser']))
{
//Getting post values
require_once 'getuserdata.php';
//1.Check if user is looged in
$loggedin = checkuserloggedin($username, $conn);
if ($loggedin)
{
$response['error']=true;
$response['message']='User is already logged in!';
}
else
{
//2.If not, insert pfleger
//Inserting log in values
if (insertuserdata($name,$username, $password, $gps, $logintime, $conn))
{
$response['error']=false;
$response['message']='Log Data added successfully';
}
else
{
$response['error']=true;
$response['message']='Could not add log in data';
}
}
}
else
{
$response['error']=true;
$response['message']='You are not authorized';
}
echo json_encode($response);
?>
use this
var request = URLRequest(url: URL(string: “url”)!)
request.httpMethod = "POST"
let userName = self.emailTextField.text!
let password = self.passtextField.text!
let postString = NSString(format: "emailId=%#&password=%action=%#",userName, password,”action name”)
request.httpBody = postString.data(using: String.Encoding.utf8.rawValue)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
do {
let jsonResults : NSDictionary = try JSONSerialization.jsonObject(with: data, options: [])as! NSDictionary
print("login json is ---%#",jsonResults)
let str = jsonResults.object(forKey: "status")as! String
if (str == "Success")
{
let newdic:NSDictionary = jsonResults.object(forKey: "response") as! NSDictionary
} catch {
// failure
print("Fetch failed: \((error as NSError).localizedDescription)")
}
}
task.resume()

Swift 3 script does not run PHP script to insert data in MySQL database

I'm new to Swift and I'm trying to make a simple app to put names in a MySQL database. When I run the Swift script in simulator, nothing changes in the database. What am I doing wrong?
Many thanks in advance!
Connect.php
//Connect to Database
$user="something_net_something";
$host="something.net.mysql";
$password="SecretPassword";
$database="something_net_something";
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");
Function.php
header('Content-Type: text/html; charset=ISO-8859-1');
//Connect to Database
include "Connect.php";
//getting values
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
//query
$QRY="INSERT INTO oneiros_aether_personage (Fname, Lname) VALUES ($fname, $lname)";
if (mysqli_query($connection, $QRY)) {
$response['error']=false;
$response['message']="New record created successfully";
} else {
$response['error']=true;
$response['message']="Error: " . $QRY . "<br>" . mysqli_error($connection);
}
echo json_encode($response);
mysqli_close($connection);
ViewController.swift
import UIKit
class ViewController: UIViewController {
//URL to our web service
let URL_ADD_PERSONAGE = "http://www.something.net/Function.php"
//TextFields declarations
#IBOutlet weak var textFieldFname: UITextField!
#IBOutlet weak var textFieldLname: UITextField!
//Button action method
#IBAction func buttonSave(sender: UIButton) {
//created NSURL
let requestURL = URL(string: URL_ADD_PERSONAGE)
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL! as URL)
//setting the method to post
request.httpMethod = "POST";
//getting values from text fields
let fname = textFieldFname.text
let lname = textFieldLname.text
//creating the post parameter by concatenating the keys and values from text field
let postParameters = "Fname="+fname!+"&Lname="+lname!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)
//creating a task to send the post request
let task = URLSession.shared.dataTask(with:request as URLRequest){
data, response, error in
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print(msg)
}
} catch {
print(error)
}
}
//executing the task
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.
}
}
To Info.plist I added
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
your code works fine with me,
check the URL_ADD_PERSONAGE variable, IBOutlet and others.
The connection logic has no error.

Read return value php on IOS application

Hello I'm writing an ios swift 3 application to communicate with a website, the app after doing a number of things should return a type value of false or true, but it does not happen you can tell me where I'm wrong and how to correct the mistake!
VALUE RETURN at swift:
....response = Optional( { URL: "http://....myurl.php"}.....
SWIFT CODE:
let myUrl = URL(string: "http://....myurl.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "username=James&password=Bond";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)");
// return false
}
print("response = \(response)")
}
task.resume()
return 0;
PHP CODE:
include 'user.php';
$user = new User();
$username= $_REQUEST["username"];
$password = $_REQUEST["password"];
if($user->login($username,$password)==true){
echo json_encode("true");
}
else{
echo json_encode("false");
}
ERROR IMAGE:
You need to look into data and not response.
And maybe you should encapsulate your return value in your PHP code, like this for example:
if($user->login($username,$password)==true){
echo '{"success":true}';
}else{
echo '{"success":false}';
}
And then get the result in swift:
func login(request_completed:#escaping (_ succeded:Bool) -> ()) {
let myUrl=URL(string: "http://....myurl.php");
var request=URLRequest(url:myUrl!)
request.httpMethod="POST"
let postString = "username=James&password=Bond";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task=URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard data != nil else {
print("no data found")
request_completed(false)
return
}
do{
if let jsonData=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary{
print(jsonData)
let success=jsonData.value(forKey: "success") as! Bool
if success{
print("login succeded")
request_completed(true)
return
}else{
print("login failed")
request_completed(false)
return
}
}else{
print("could not parse json")
request_completed(false)
}
}catch{
print("request failed")
request_completed(false)
}
})
task.resume()
}

Categories