POST json object in a form variable on a sever - php

hello I am working on IOS SWIFT 2. I NEED to send the json object in a variable so that I can access the json object like that
$json = $_POST['json'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
right now the data is posting on server like this
{
"email" : "email",
"password" : "password"
}
This is the code I am using
func post() {
let url:String = "http://example.com/test.php"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let params = ["email":"email", "password":"password"] as Dictionary<String, String>
//let request = NSMutableURLRequest(URL:url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print("dataString is \(dataString)")
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else { return }
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// 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
let success = parseJSON["success"] as? Int
print("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)
print("Error could not parse JSON: \(jsonStr)")
}
})
task.resume()
}
I want to pass the json above in a form variable called 'json'.

I would highly recommend using a Library, such as Alamofire to handle this.
Doing it yourself is tedious.
Once added to your Swift Project, you can send JSON parameters really, really elegantly:
Example from the Github page:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)
Then you can use your existing PHP code to process your JSON.
Edit:
Also handling JSON is really elegant too:
Alamofire.request(.POST, url, etc).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

Related

Swift 4 Codable Struct with Post Request

i want to send a url.request(POST)with a Codable Struct like That :
struct Picklist : Codable {
var id = Int()
var ean = String()
var position = String()
}
and my request is like that :
let request = NSMutableURLRequest(url: NSURL(string: "http://XXX.XX.XX.XX/NEW/index.php")! as URL)
request.httpMethod = "POST"
let myID = Picklist.init(id: 3, ean: "asdf", position: "q")
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(myID)
request.httpBody = jsonData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
} catch {
print("ERROR")
}
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}
task.resume()
and of the Server Side i have this PHP Script:
<?php
print_r($_POST);
?>
but i am receiving :
responseString = Optional(Array
(
[{"id":3,"ean":"asdf","position":"q"}] =>
)
my Problem is that i can't get the Keys with the value on my PHP..
what is wrong with the code ?
Finally, answer is :
if you want to work with the response string just go and decode the "data"
For example :
guard let data = data else {return}
do{
let realData = try JSONDecoder().decode(response.self, from: data)
completion(realData)
}catch let jsonErr{
print(jsonErr)
}
in realData you can work with the data, but you need to create Codable/decobale Struct to work with
response is my coddle/decodable struct
or :
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}

Error Domain=NSCocoaErrorDomain Code=3840 when trying to send data from Swift to PHP

I'm trying to send data from Swift to PHP but whatever i try, it won't work. The latest error i'm getting is the
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."' and
'UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}' errors.
I have no idea where the problem is, as i validated my JSON and the PHP side is working when using Postmen. So the problem has to be in the Swift code i guess..
This is my Swift code:
let payload = try! JSONEncoder().encode(bon)
let payloadString = String(data:payload, encoding: .utf8)!
//URL to our web service
let URL_SAVE_TEAM = URL(string:"http://trinto.kuppeveld.xyz/API/createteam.php")
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: URL_SAVE_TEAM!)
//setting the method to post
request.httpMethod = "POST"
//adding the data to request body
request.httpBody = payloadString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//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;
}
print("-----")
print(String(data: data!, encoding: String.Encoding.utf8)!)
print("-----")
//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()
When i print payloadString it returns the JSON as following:
{"datum":"11-12-2017","winkel":"jumbo","producten":[{"prijs":"2.50","naam":"ham"},{"prijs":"1.20","naam":"brood"}],"tijd":"15:07"}
And to be sure, here is my PHP code (which works with Postmen, as i mentioned):
$json = file_get_contents('php://input');
$array = json_decode($json, true);
echo $json;
var_dump($array);
var_dump($array) return NULL for some reason, but when i use Postmen it has no problem giving back the JSON as i inserted.
Has anybody got a clue how to fix my problem? Thanks in advance!

Swift 3 problems Parsing json response

I am new on Swift but I was follwoing some examples like how to make a login app sending username and password fields to a php file and getting the json response back.
When I print my responseString I get:
[{"userid":1,"username":"rodrigo","password":"minhoca","groupname":"couple"}]
But when I try to parse the json I never can set the username variable because never gets into that part of the code, I just get "here"
Thanks for the help
func sendLoginInfo(username: String, password: String) -> String{
if let url = URL(string: "myphpurl"){
let request = NSMutableURLRequest(url:url)
request.httpMethod = "POST";// Compose a query string
let postString = "?username=\(myUsername)&password=\(myPassword)"
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("1\(error)")
}
else{
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("response string = \(responseString!)")
}
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
// Get value by key
let firstNameValue = convertedJsonIntoDict["username"] as? String
print("here = \(firstNameValue!)")
}
else{
print("here")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
return ""
}
Change the NSDictionary to NSArray in your code because you are getting an array and trying to convert to dictonary:
if let convertedJson = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray
get the object at index 0 which will give you dictonary & then you can get username
So the Final code will be:
func sendLoginInfo(username: String, password: String) -> String{
if let url = URL(string: "myphpurl"){
let request = NSMutableURLRequest(url:url)
request.httpMethod = "POST";// Compose a query string
let postString = "?username=\(myUsername)&password=\(myPassword)"
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("1\(error)")
}
else{
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("response string = \(responseString!)")
}
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
// Print out dictionary
print(convertedJsonIntoDict)
// Get value by key
let firstNameValue = (convertedJsonIntoDict[0] as! NSDictionary)["username"] as? String
print("here = \(firstNameValue!)")
}
else{
print("here")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
return ""
}

How to Parse a JSON with Swift on IOS, sent from a PHP service script?

I'm having trouble parsing a JSON, sent from a PHP script, on IOS using swift. I just started learning IOS development this week and also had never worked with JSON before so any help would be greatly appreciated on parsing this correctly. I'm sending a result from a mysql query as a JSON to the app. Here is my swift code and the error log in which you can see the object received by the http service.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let secondViewController:VC2 = segue.destinationViewController as! VC2
let myUrl = NSURL(string: "myscriptaddress");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "condition=" + String(currentval);
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
secondViewController.mystring = "getting ready"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Success")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error can't parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
And now the error log:
Error could not parse JSON: Optional([{"unidad":"sanfrancisco","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"pediatricouniversitario","capacidad":"15","uso":"5","telefono":"num"},{"unidad":"sanjorge","capacidad":"15","uso":"7","telefono":"num"},{"unidad":"himacaguas","capacidad":"20","uso":"4","telefono":"num"},{"unidad":"himabayamon","capacidad":"20","uso":"8","telefono":"num"},{"unidad":"sanlucas","capacidad":"10","uso":"8","telefono":"num"},{"unidad":"auxiliomutuo","capacidad":"15","uso":"11","telefono":"num"}])
Its failing to unwrap the JSON data as a dictionary type. The JSON string provided is an array of objects.
Try this in your JSONObjectWithData call:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String : AnyObject]]

Empty array when making a HTTP Post Request to PHP from Swift App

Hi I am trying to connect my iOS app to my PHP API.
I am sending JSON POST to my PHP API but I am getting an empty array as Output.
My Swift Code
#IBAction func JSONButtonAction(sender: AnyObject) {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
var image : UIImage = clickedPhotoView.image!
var imageData = UIImagePNGRepresentation(image)
let base64String = imageData.base64EncodedStringWithOptions(.allZeros)
let params:[String: AnyObject] = [
"email" : usr,
"image" : base64String ]
let url = NSURL(string:"http://localhost/app/")
let request = NSMutableURLRequest(URL: url!)
let boundaryConstant = "Boundary-7MA4YWxkTLLu0UIW"; // This should be auto-generated.
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)
let task = session.dataTaskWithRequest(request) {
data, response, error in
// println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("\(responseString)")
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error)")
return
}
// handle the data of the successful response here
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
//println(result)
}
task.resume()
}
PHP Code
print_r($_POST);
Output is
array(
)
But when I use
$data = json_decode(file_get_contents('php://input'), true);
It works fine
I dont know why $_POST is not working.
If your intent is actually to send a string, then you should change the content-type:
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
Tested your exact code with this modification on my tests server:
Otherwise, check #kekub's comment.

Categories