php can't get parameter from Xcode program writtern by Swift - php

I cannot get the parameter sent from the swift code. If i ignore the parameter i can got return result. Please help. THX
Swift Code:
var url: NSURL = NSURL(string: urlPath)!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.timeoutInterval = 60
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
var searchString = ""
var bodyData: NSString = "brandCode=BU&model=test1234"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
var connection:NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
PHP Code:
$brandCode=$_POST['brandCode'];
$model=$_POST['model'];
$cnx=odbc_connect('testODBC','testing','testing');
$sql="select * from brand where brand='".$brandCode."' and model='".$model."'";
$cur= odbc_exec($cnx, $sql);
while($info = odbc_fetch_array($cur))
{
$resultArray[]=array($info);
}
echo json_encode($resultArray);

Try with this code
var URL: NSURL = NSURL(string: "http://example.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
var bodyData = "brandCode=BU&model=test1234"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

I'm not very strong in PHP, but it looks to me like you are trying to extract the model value as an URL parameter rather than from the body of the message.
You should either append your "brandCode=BU&model=test1234" string directly to your URL:
http://myurl.php?brandCode=BU&model=test1234
Or build the URL using NSURLComponents.
Adding parameters to the URL is different then transmitting data in the body of A POST.

Related

Swift - Send array to PHP

I want to send an array to my server with URLRequest post method but it doesn't work.
When I send a string it works well but with an array not work. I can't get data with array post.
Below code works great:
func getData() {
pageid = 1
var request = URLRequest(url: URL(string: "http://localhost/index.php")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
request.httpMethod = "POST"
let postString = "page=" + String(pageid);
request.httpBody = postString.data(using: .utf8)
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
do {
let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>
let itemsArray = response["items"] as! [AnyObject]
for itemObj in itemsArray {
print(itemObj)
}
} catch {
}
}).resume();
}
my array is:
var ids: [Int] = [1, 5, 8]
i try to send it like this but it doesn't work
let postString = "page=" + String(ids.description)
my php code:
<?php
$pageid = $_POST['page'];
....
?>

Swift - post to server multiple values

I have a function that send two string values "Name and Text" to a server.
When the post method is sent the php file send an email with this two values.
Everything works if I send only one value from my iOS app however, if I try to send two or more value I don't get any email.
The code I am using is:
func postToServerFunction() {
var textFromapp: NSString = sendValueText.text
var nameFromapp: NSString = sendValueName.text
println("Button Pressed")
var url: NSURL = NSURL(string: "http://example.com//iOS/send_ios.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
var bodyData = "data=" + (textFromapp as String) //data to send
var bodyName = "name=" + (nameFromapp as String) //data to send
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
request.HTTPBody = bodyName.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
// Yes, Do something.
}
}
}
}
How could I tell the HTTPBody to look at both values?
for Future reference here how I solved it:
var bodyData = "data=" + (textFromapp as String) + "&name=" + (nameFromapp as String)
any other suggestion is welcome
Look at this answers. Fun(ctional) is the most beautiful.
function encodeData(data) {
return Object.keys(data).map(function(key) {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}

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.

Swift upload file to PHP server

So I'm uploading a file from swift to a PHP server, the POST request arrives as expected with headers and all but I'm unable to get anything out of $_FILES. It's just an empty array.
I'm clearly doing something wrong on the Swift side, this is my code:
func testUpload(){
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("someTestFile", ofType: "zip")!
var data: NSData = NSData(contentsOfFile: path)!
var request = NSMutableURLRequest(URL: NSURL(string: "http://testsite.com/upload")!)
request.HTTPMethod = "POST"
let boundary = "----------ds2Gry67efddagdfsfhsHF"
let contentType = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField:"Content-Type")
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
self.uploadFiles(request, data: data)
}
func uploadFiles(request: NSURLRequest, data: NSData) {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
var task = session.uploadTaskWithRequest(request, fromData: data)
task.resume()
}
I'm pretty sure I'm missing something, I just can't figure out what it is...
POST method ,you need add header application/x-www-form-urlencoded

json swift ios - sending parameters to a php-sql

Hello I am trying to send a couple of parameters from an SWIFT IOS application to a PHP-SQL database using JSON. Has tried several examples both sycronus and asyncronus but I do not get it to work.
Keep troubling with the converting of the JSON parameter string to a format that will be received on the other side.. (when i try in the browser it will work..but not from the app itself)
Here is the code - from PLAYGROUND
(The response is API Response: OPTIONAL (Missing JSON)
// Playground - noun: a place where people can play
import UIKit
import CoreLocation
var str = "Hello, playground debug use of JSON and PHP"
import Foundation
let url = NSURL(string:"http://mywebserver-replaced.no/POSITION/update.php?")
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 = " "
dataString = "json={\"FBID\":10,\"Driving\":1,\"Latitude\":\"68.123\",\"Longitude\":\"22.124\",\"Time\":\"18:24\",\"Date\":\"07.10.2014\",\"Heading\":90}"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
println("\(requestBodyData)") // This will print "Optional(<6a736f6e...and so on..
// And except the optional it is quite correct.. json={
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// set content length
// NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")
What am i dooing wrong?
You are setting wrong Content-Type
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
should be
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
And also
dataString = "json={\"FBID\":10,\"Driving\":1,\"Latitude\":\"68.123\",\"Longitude\":\"22.124\",\"Time\":\"18:24\",\"Date\":\"07.10.2014\",\"Heading\":90}"
Remove the json=, which makes the body not a valid json.

Categories