I have a php script on my server and I am trying to post data from my ios app, but when I print the post variables I get a nil. Any idea why that is?
Swift
let url: NSURL = NSURL(string: "https://xxxxxx.com/myFile.php")!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
let bodyData = "username=\(username.text)&password=\(password.text)"
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main)
{
(response, data, error) in
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
//
print("response \(responseString)")
}
PHP
print_r($_POST); //prints: ([username] => xxxxxx [password] => yyyyyy)
json_encode($postVarUser);
json_encode($postVarPass);
May be it is the problem of echo($postUser);
just use json_encode($postUser);
Related
I am trying to make an api call I build the json object. But the data is not being passed I believe it is the formatting of the data when passed the service only has examples in php which i have posted below
API Docs: http://middleware.idxbroker.com/docs/api/methods/index.html#api-Leads-putLead
php call
// PUT lead in to IDX Broker
$url = 'https://api.idxbroker.com/leads/lead';
$data = array(
'firstName'=>$firstname,
'lastName'=>$lastname,
'email'=>$email
);
$data = http_build_query($data); // encode and & delineate
$method = 'PUT';
Swift Code to build json object
/// Create lead from text fields
let jsonObject: [String: String] = [
"firstName": (firstName.text! as String),
"lastNmae": lastName.text!,
"email": Email.text!,
"phoneNumber": phoneNumber.text!,
"city": (city.text as AnyObject) as! String,
"recieveUpdates": (switchIsChanged(recieveUpdates: recieveUpdates) as AnyObject) as! String
]
The API Call
class func putLead(lead: AnyObject){
let urlString = "https://api.idxbroker.com/leads/lead"
let url = NSURL(string: urlString)
print(lead)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
/******************** Add Headers required for API CALL *************************************/
downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
downloadTask.setValue(APICalls.getAccessKey(), forHTTPHeaderField: "accesskey")
downloadTask.setValue("json", forHTTPHeaderField: "outputtype")
downloadTask.httpMethod = "PUT"
downloadTask.httpBody = (lead as? Data)
/******************** End Headers required for API CALL *************************************/
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
/// Status Returned from API CALL
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
}
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData ?? "No Return")
}).resume()
/******** End URL Session **********/
}
Working Version
let newLead = "firstName=\(firstName.text!)&lastName=\(lastName.text!)&email=\(Email.text!)&phoneNumber=\(phoneNumber.text!)&city=\(String(describing: city.text))&recieveUpdates=\((switchIsChanged(recieveUpdates: recieveUpdates) as AnyObject) as! String)"
let newData = newLead.data(using: String.Encoding.utf8)
/// API Call with passing json String
APICalls.putLead(lead: newData!)
I was able to get it working by making the following changes to your putLead() function:
class func putLead(lead: [String:String]){
let urlString = "https://api.idxbroker.com/leads/lead"
let url = NSURL(string: urlString)
var httpBodyString = ""
for (key,value) in lead{
let currentKey = key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let currentValue = value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
httpBodyString += "\(currentKey!)=\(currentValue!)&"
}
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
/******************** Add Headers required for API CALL *************************************/
downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
downloadTask.setValue(<API_KEY_HERE>, forHTTPHeaderField: "accesskey")
downloadTask.httpMethod = "PUT"
downloadTask.httpBody = httpBodyString.data(using: String.Encoding.utf8)
/******************** End Headers required for API CALL *************************************/
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
/// Status Returned from API CALL
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
}
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData ?? "No Return")
}).resume()
/******** End URL Session **********/
}
I am setting up payment processing for my OSX desktop app in swift. Since there is no SDK for OSX, I am using a Web View via the PHP SDK for Braintree. I want to pass some POST data so that the price of a product is coming dynamically from my App, but it seems to not be recognized and is underfined according to PHP errors.
I know how to send POST variable to a PHP script and have done it many times, but I have a feeling something might not be right with my swift code. My PHP error is: "Notice: Undefined variable: price"
PayPal.swift
import Cocoa
import WebKit
class PayPal: NSViewController {
#IBOutlet weak var paypalWebView: WebView?
override func viewWillAppear() {
self.view.window!.title = "Payment"
}
override func viewDidLoad() {
super.viewDidLoad()
setupPP()
}
func setupPP(){
let request: NSURL = NSURL(string: "http://")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: request as URL)
urlRequest.httpMethod = "POST"
let postString = "price=45"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8);
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
let requesting = NSURLRequest(url: request as URL)
DispatchQueue.main.async(){
self.paypalWebView?.mainFrame.load(requesting as URLRequest)
}
}
}
Braintree PHP Script
if(isset($_POST["price"])){
$price = $_POST["price"];
}
<?php $tr_data = Braintree_TransparentRedirect::transactionData(
array('redirectUrl' => "http://" ,
'transaction' => array('amount' => $price, 'type' => 'sale'))) ?>
Also the Paypal View that is essentially a web view is being activated when a user clicks on a button via a segue. I don't know if that would have anything to do with it or not?
I ended up getting it to work!
Paypal.swift
import Cocoa
import WebKit
class PayPal: NSViewController {
#IBOutlet weak var paypalWebView: WebView?
override func viewWillAppear() {
self.view.window!.title = "Payment"
}
override func viewDidLoad() {
super.viewDidLoad()
setupPP()
}
func setupPP(){
let request: NSURL = NSURL(string: "http://")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: request as URL)
urlRequest.httpMethod = "POST"
let postString = "amount=29.95"
urlRequest.httpBody = postString.data(using: String.Encoding.utf8);
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: .utf8)
print("responseString = \(responseString)")
}
paypalWebView?.mainFrame.load(urlRequest as URLRequest)
task.resume()
}
}
PHP Script
<?php
if (isset ($_POST['amount'])) {
$amount = $_POST['amount'];
}
$tr_data = Braintree_TransparentRedirect::transactionData(
array('redirectUrl' => "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH),
'transaction' => array('amount' => $amount, 'type' => 'sale')))
?>
I am trying to send data via POST to a server in Swift 2.1, however, the server never appears to receive any of the data.
Swift:
let url = NSURL(string: "http://www.myserver.com/test.php");
let request = NSMutableURLRequest(URL:url!)
request.HTTPMethod = "POST";
let postString = "firstName=TestName1&lastName=TestName2";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = NSURLSession.sharedSession();
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding) as NSString!
print("Data: \(urlContent)");
});
task.resume();
PHP:
<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$returnValue = array(“firstName”=>$firstName, “lastName”=>$lastName);
// Send back request in JSON format
echo json_encode($returnValue); ?>
Returns:
Data: {"firstName":null,"lastName":null}
I have canvased the web in an attempt to solve this problem, however, most of the solutions are out of date as they do not conform to the deprecations and changes brought with Swift 2.
Any ideas?
By removing the following lines of code, I got the data to return correctly:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
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.
I simply want to POST some data from Swift to a PHP script. I've Googled for about two days on this and everyone seems to be doing the same thing, but it's not working for me. I have this Swift code triggered on viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
let request = NSMutableURLRequest(URL: NSURL(string: "http://mywebsite.com/scriptToHandlePOST.php")!) // it forces me to add the !
request.HTTPMethod = "POST"
var err: NSError?
let postString = "var1=value1&var2=value2".dataUsingEncoding(NSUTF8StringEncoding)
var postLength:NSString = String( postString!.length )
request.HTTPBody = postString
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println(response) // this returns a 200
println(strData!) // this returns an empty array of the $_POST variable
}
task.resume() // this is needed to start the task
}
My PHP script is simply just trying to get $_POST data:
<?php
print_r($_POST);
?>
Since the $_POST returns an empty array I suspect the POST request is never making it to my website. Do you see anything wrong in the code?