SWIFT and PHP exchange with JSON - php

iam using swift function to send POST query to php script
func post_retJSON_inJSON(params : Dictionary<String, String>,tourl:String)
{
let myUrl = NSURL(string: tourl);
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
// You can print out response object
println("response = \(response)")
// Print out response body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
var firstNameValue = parseJSON["firstName"] as? String
println("firstNameValue: \(firstNameValue)")
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
task.resume()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
With this php
$firstName= $_POST["firstName"];
$lastName = $_POST["lastName"];
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);
// Send back request in JSON format
echo json_encode($returnValue);
AND then in swift i have a response
Optional({"firstName":null,"lastName":null})
I think i already try everything but I cant get in PHP parametres sended by SWIFT query. Help me please to figureout it!!!

solved with this php and the same swift as in top
// Read request parameters
$postdata = json_decode(file_get_contents("php://input"),TRUE);
$firstName= $postdata["firstName"];
$lastName = $postdata["lastName"];
// Store values in an array
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);
// Send back request in JSON format
echo json_encode($returnValue);

Related

swift 3 with Mysql

I am trying to make registration in swift3 with mysql
but there is some thing wrong ,
when I run my app and make register return msg "some fields are empty"
In php code:
$fullname = htmlentities($_REQUEST["fullname"]);
$username = htmlentities($_REQUEST["username"]);
$email = htmlentities($_REQUEST["email"]);
$password = htmlentities($_REQUEST["password"]);
$phone = htmlentities($_REQUEST["phone"])
swift code:
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://localhost/php/register.php?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "fullname=\(FirstName.text)%20\(LastName.text)&username=\(UserName.text)&email=\(Email.text)&password=\(Password.text)&phone=\(Phone.text)"
request.httpBody = body.data(using: String.Encoding.utf8)
let task = session.dataTask(with: url!) {data, response, error in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print(json)
}
} catch {
print("error in JSONSerialization")
}
}
}
task.resume()
I think you missed this
let task = session.dataTask(with: request) {data, response, error in
replace url with request

Return json value with php from swift iOS

Hello I have a small a problem with the code below, Xcode print this error:
ERROR: json error: Error Domain=NSCocoaErrorDomain Code=3840 "No
value." UserInfo={NSDebugDescription=No value.}
SWIFT CODE:
let yourUrl=“mylink.php”
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL!)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
let dataString = "Email=\(Email.text)&Password=\(Password.text)"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()
PHP CODE:
mylink.php
<?php
header("Content-Type: application/json");
$email = $_POST["Email"];
$password = $_POST["Password"];
$stat=“myvalue”;
return json_encode($stat);
?>
How can I solve this error?

Request on php script with nsurlconnection

i try to send value to server with this code by i have an error on this line:
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
the error is : EXTRA ARGUMENT IN CALL "error"
var yourUrl="mylink"
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "
V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "my value"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
if let dataFromString = results!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
if(json=="0"){
print("\n Dati non validi");
}
else{
print("\n Account creato");
}
}
You should never use sendSynchronousRequest as it is a blocking call. Also it is deprecated from iOS 9.0 onwards. Instead you can use NSURLSession. Try out following code
var yourUrl="mylink"
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = "my value"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()

IOS SWIFT 2 - Http Post json array to server

I want to send data from my iOS app to a PHP sever in JSON format. I am doing this at the backend with the following code:
$json = $_POST['json'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
I want to send data in a JSON variable such that I can accept the data in
the JSON variable and then extract the fields one by one.
At the moment, I am doing this in my iOS app with the following Swift code:
func login(){
let email:NSString = txtEmail.text!
let password:NSString = txtPassword.text!
let post:NSString = "username=\(email)&password=\(password)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://example.com/test.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
let success:NSInteger = jsonData!.valueForKey("success") as! NSInteger
NSLog("Success: %ld", success);
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}
I think I have to send a JSON array, but I don't know how can I save the variables in the array and send the JSON array to the PHP server. Anyone have any ideas?
You can do this by creating an array of dictionaries:
var user_outer_arrary = [[String:Any]]()
var user_inner_array = [String: Any]();
var jsonData : Data? = nil
let user_data :[String:Any]=["email": email,"password": password];
user_outer_arrary.append(user_data);
user_inner_array=["json": user_outer_arrary]
Then convert to JSON:
do
{
jsonData = try JSONSerialization.data(withJSONObject: user_inner_array, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch
{
}

PHP: how to get variables from a JSON(sent from a Swift iOS app) and respond with a JSON

I am developing an iOS app with Swift that should fetch some data from a MySQL database according to the user's location. I don't know PHP and I couldn't find a resource where it explains how to receive data from an app.
I have this PHP code:
<?php
// Create connection
$con=mysqli_connect("localhost","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM *******";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo "{ \"posts\": ";
echo json_encode($resultArray);
echo "}";
}
// Close connections
mysqli_close($con);
?>
as you can see when it is called it gets all the data from a table and returns it as a JSON. The next step that I want to do is to send my location from the Swift app with this code:
#IBAction func submitAction(sender: AnyObject) {
//declare parameter as a dictionary which contains string as key and value combination.
var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>
//create the url with NSURL
let url = NSURL(string: "http://myServerName.com/api") //change the url
//create the session object
var session = NSURLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
courtesy from http://jamesonquave.com/blog/making-a-post-request-in-swift/
and I don't know how to "get"(accept, what function to use) this JSON:
{"items": [
{
"minLat": "43.000000",
"maxLat": "44.000000",
"minLon": "-79.000000",
"maxLon": "-78.000000",
}
]
}
from the app in order to have something like this in PHP:
$minLat = $json['minLat'];
$maxLat = $json['maxLat'];
$minLon = $json['minLon'];
$maxLon = $json['maxLon'];
$sql = "SELECT * FROM ******* WHERE latitude BETWEEN".$minLat." AND ".$maxLat." AND longitude BETWEEN ".$minLon." AND ".$maxLon;
Thank you
The answer is actually incredibly stupid-easy:
firstly nothing worked before I commented these two lines:
request.addValue("application/json", forHTTPHeaderField: "Content--Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Then I used a string instead of a JSON to send the POST data(it surely works with a JSON also, but this is what works at this moment):
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "minLat=43.0&maxLat=44.0&minLon=26.0&maxLon=27.0";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
and at the server side simply:
$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLat"];
$maxLon = $_REQUEST["maxLat"];
:|

Categories