So i followed this suggestion: https://stackoverflow.com/a/27014372/4751488.
When i run my script the photo wont upload. I get no error on the JSON response only that the image has not been uploaded. Anny ideas?
my main function:
var image : UIImage = UIImage(named:"record")!
let imageData2 = UIImagePNGRepresentation(image)
imageViewController.image = image
var parameters = [
"pic" :NetData(data: imageData2!, mimeType: MimeType.ImageJpeg ,filename: "customName.jpg"),
"otherParm" :"Value"
]
let urlRequest = self.urlRequestWithComponents("http://www.xxx.xx/uploadPhoto.php", parameters: parameters)
Alamofire.upload(urlRequest.0, urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { (request, response, JSON, error) in
println("REQUEST \(request)")
println("RESPONSE \(response)")
println("JSON \(JSON)")
println("ERROR \(error)")
}
and my urlRequestWithComponents looks like this :
func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {
// create url request to send
var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
//let boundaryConstant = "myRandomBoundary12345"
let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())"
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
if value is NetData {
// add image
var postData = value as! NetData
//uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// append content disposition
var filenameClause = " filename=\"\(postData.filename)\""
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentDispositionData!)
// append content type
//uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this.
let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentTypeData!)
uploadData.appendData(postData.data)
}else{
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
php code :
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = "/var/www/html/upload/uploads/";
// PS: custom filed name : pic
$uploadfile = $uploaddir . basename($_FILES['pic']['name']);
if (move_uploaded_file($_FILES["pic"]["tmp_name"], $target_file)) {
$array = array ("code" => "1", "message" => "successfully");
} else {
$array = array ("code" => "0", "message" => "Possible file upload attack!".$uploadfile);
}
echo json_encode ( $array );
?>
rsponse in xcode:
JSON Optional({
code = 0;
message = "Possible file upload attack!/var/www/html/upload/uploads/customName.jpg";})
ERROR nil
Old topic but if you're looking for an answer, you use the function move_uploaded_file with the var $target_file which is not initialized.
You should have used $uploadfile
Related
I am trying to upload a file (in this case I'm trying with an image, but I would need to be able to upload any kind of file, especially a video file) to my server.
This is my PHP code, and it works fine on a server-side:
<?php include '_config.php';
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString."_".$_POST['fileName'];
}
?>
This is my Swift 5 function:
func uploadFile(_ aImage:UIImage, maxWidth:CGFloat, completion: #escaping (_ fileURL:String?) -> Void) {
showHUD()
let image = scaleImageToMaxWidth(image: aImage, newWidth: maxWidth)
// Generate a random filename
var filename = ""
for _ in 0..<20 {
let randomChar = Int(arc4random() % UInt32(charsForRand.count))
filename += charsForRand[randomChar]
}
filename += "__image.jpg"
print("FILENAME: \(filename)")
let boundary = UUID().uuidString
let fieldName = "reqtype"
let fieldValue = "fileupload"
let fieldName2 = "userhash"
let fieldValue2 = "caa3dce4fcb36cfdf9258ad9c"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
var urlRequest = URLRequest(url: URL(string: DATABASE_PATH + "upload-file.php")!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(fieldName)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(fieldValue)".data(using: .utf8)!)
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(fieldName2)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(fieldValue2)".data(using: .utf8)!)
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"fileToUpload\"; fileName=\"\(filename)\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
data.append(image.jpegData(compressionQuality: 1.0)!)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
// Send a POST request to the URL, with the data we created earlier
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error != nil { print("\(error!.localizedDescription)") }
guard let responseData = responseData else {
DispatchQueue.main.async {
self.simpleAlert("Something went wrong while uploading, try again.")
}
completion(nil)
return
}
if let response = String(data: responseData, encoding: .utf8) {
completion("\(DATABASE_PATH)\(response)")
print("UPLOAD URL: \(DATABASE_PATH)\(response)")
}
}).resume()
}
I call that function in my ViewController as follows:
uploadFile(UIImage(named: "default_avatar")!, maxWidth: 300) { (fileURL) in
if fileURL != nil {
print("FILE URL: \(fileURL!)")
}
}
But this is what I get in the Xcode console:
FILE URL: https://example.com/uploads/8iWQOrwr0wgNDor8XNhX_
UPLOAD URL: https://example.com/uploads/8iWQOrwr0wgNDor8XNhX_
This means that my function doesn't append "__image.jpg" string to the filename variable, and it also doesn't upload my image to the uploads folder on my server.
What am I doing wrong? If I call my PHP script from a form with an input of type file, it works like a charm., so my PHP script is fine, so I'm surely doing something wrong in the Swift function.
I've found a solution, here's my edited Swift 5 function, which now can also accept mp4 video files, not just jpg or png images:
func uploadFile(fileData:Data, fileName:String , completion: #escaping (_ fileURL:String?, _ error:String?) -> Void) {
print("FILENAME: \(fileName)")
let boundary: String = "------VohpleBoundary4QuqLuM1cE5lMwCy"
let contentType: String = "multipart/form-data; boundary=\(boundary)"
let request = NSMutableURLRequest()
request.url = URL(string: DATABASE_PATH + "upload-file.php")
request.httpShouldHandleCookies = false
request.timeoutInterval = 60
request.httpMethod = "POST"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"fileName\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(fileName)\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n".data(using: String.Encoding.utf8)!)
// File is an image
if fileName.hasSuffix(".jpg") {
body.append("Content-Type:image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
// File is a video
} else if fileName.hasSuffix(".mp4") {
body.append("Content-Type:video/mp4\r\n\r\n".data(using: String.Encoding.utf8)!)
}
body.append(fileData)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response, error == nil else {
DispatchQueue.main.async { completion(nil, error!.localizedDescription) }
return
}
if let response = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
print("XSUploadFile -> RESPONSE: " + DATABASE_PATH + response)
DispatchQueue.main.async { completion(DATABASE_PATH + response, nil) }
// NO response
} else { DispatchQueue.main.async { completion(nil, E_401) } }// ./ If response
}; task.resume()
}
Here's how I use that function:
let imageData = UIImage(named: "my_img")!.jpegData(compressionQuality: 1)
uploadFile(fileData: imageData!, fileName: "image.jpg") { (fileURL, e) in
if e == nil {
print("FILE URL: " + fileURL!)
}}
This works 100%.
I have a problem trying to upload an image in swift to a PHP server. Everything looks good till the php processes the file. In that moment I get the error.
The relevant part of the swift code is:
func myImageUploadRequest(image: UIImage, realfilename: String)
{
let myUrl = NSURL(string: "http://www.ignistudios.com/boda/postImage.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "username",
"lastName" : "lastname",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
print(imageData.debugDescription)
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", realfilename: realfilename, imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, realfilename: String?, imageDataKey: NSData, boundary: String) -> NSData {
var body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = realfilename
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
And the php is
<?php
$uploaddir = '/fotos/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
And last, the error I get is:
****** response data =
Upload failedHere is some more debugging info:Array
(
[file] => Array
(
[name] => Optional(\"boda20160428_135709.jpg\")
[type] =>
[tmp_name] =>
[error] => 1
[size] => 0
)
)
Any tip would be very much appreciated.
It looks like Marc B has commented with the answer which is that it is a PHP file upload size issue.
However in cases like this it is worth testing each link in the chain separately. For example testing and reviewing the output of createBodyWithParameters. Create a test and run it there to check that the headers are properly formed. Especially make sure that the string encoding is correct. I'm not familiar with the appendString method on NSMutableData.
It should be possible to feed that output more directly into the server to eliminate other potential issues.
The correct answer is that the image is too big and you need to compress the image before uploading it, using this
UIImageJPEGRepresentation(image,0.2)
When the image is small enough you will get your tmp name
I was wondering how I would get php script to retrieve my base64 encoded image then write to server? I tried doing a post dump from my php script and I keep getting a response that it is empty. I've tried following a few other stackoverflow guides on this but none of them use a factory afaik.
js
var app = angular.module("app", ["ui.bootstrap"]);
//http://stackoverflow.com/questions/18571001/file-upload-using-angularjs
app.factory('API', function ($http) {
return {
uploadImage: function (image) {
return $http.post('/js/upload.php', image);
}
}
});
app.controller('MainController',['$scope', '$http', 'API', function($scope, $http, API) {
$scope.imageUrl = "";
$scope.template = "";
$scope.templates = [
'select an option...',
'MakeGray',
'Canny'
];
$scope.template = $scope.templates[0];
$scope.add = function() {
var f = document.getElementById('fileToUpload').files[0]; // name of image
var files = document.getElementById('fileToUpload').files;
var r = new FileReader();
r.onload = function(event){
console.log(event.target.result);
}
r.onloadend = function(e) {
var data = e.target.result;
var formData = new FormData();
$("#img1").prop("src", data);
$("#img2").prop("src", data);
formData.append("fileToUpload", f,f.name);
API.uploadImage(formData)
.success(function (imgUrl) {
$scope.imageUrl = imgUrl;
})
.error (function (error) {
});
}
r.readAsDataURL(f);
}
}]);
php
<?php
if(isset($_FILES['fileToUpload'])){
$errors= array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../uploads/".$file_name);
echo " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
Angular have a particularity in concern the uploading.
First, you have to kno, angular's default transformRequest function will try to serialize our FormData object, so we override it with the identity function to leave the data intact.
Next, the default content-type header for POST requests is "application/json", so you must to change this because you want to upload a file.
By setting 'Content-Type': undefined, the browser sets the Content-Type to multipart/form-data himself and fills in the correct boundary.
Manually setting 'Content-Type': multipart/form-data will fail to fill in the boundary parameter of the request.
Look about others possible issues : https://docs.angularjs.org/api/ng/service/$http
Now you can get you image from $_POST global array of PHP.
Fixed code
uploadImage: function (formData)
{
return $http.post('js/upload.php', formData,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
Note:
That the below service uses the FormData object which is not supported by IE9 and earlier.
I am trying to work with a swift code to pass vars to php and a response back to swift. this all goes smooth with the following code. This is just a simple peice of code to get things going. It gives me the correct connection and results, how ever i have to pass loads of data which should be in an array i guess. But when i try to send through more data in a array i don't see anything. In php i would explode the results to get them one by one but how do i get loads of values to variables so i can use them again?
below is my code
<?php
require('conn.php');
header('Content-type: application/json');
if($_POST) {
$database =trim ($_POST['database']);
$engine = trim($_POST['engine']);
$name = "William";
$results = Array("name" => $name
);
echo json_encode($results);
}/*end if POST*/
?>
this is the swift code
let data:NSString = ("bfdprofile" as NSString)
let engine:NSString = "account" as NSString
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
let url = NSURL(string:"xxxxx.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 = "data=\(data)&engine=\(engine)"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// 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)
if let results = NSJSONSerialization.JSONObjectWithData(reply!, options: nil, error: &error) as? [String: String]{
if let name = results["name"]{
labelTestOutput.text = name as? String
}
}
Thanks for the help
You can do it asynchronously with Alamofire library as simple as that:
typealias JSONdic = [String: AnyObject]
let param = ["data": "somedata", "engine": "someEngine"]
Alamofire.request(.POST, URLString: "xxxxx.php", parameters: param).responseJSON() {
(_,_,json,_) in
if let json = json as? JSONdic, name = json["name"] as? String {
// do something with name
}
}
I am trying to send JSON from PHP to iOS Swift.
But when I decode json in Swift, the value is "",
although the key comes out well.
I learned the variables in PHP have to be UTF-8 encoded, but same problem occurs even after the encoding.
Can anyone help me how to solve this issue?
You can just copy & paste both PHP and Swift code.
If I run this code in a web browser, I get
{"upDirection":"\u00ec\u00a2\u0085\u00ed\u0095\u00a9\u00ec\u009a\u00b4\u00eb\u008f\u0099\u00ec\u009e\u00a5"}
This is the code:
<?php
//if(isset($_POST["stationId"]) && isset($_POST["dateTime"])) {
include('simple_html_dom.php');
/* for testing */
$station_id = "923";
$date_time = "201507091750";
$url = "http://m.map.naver.com/pubtrans/inquireSubwayDepartureInfo.nhn?stationID=".$station_id."&inquiryDateTime=".$date_time."00&count=5&caller=mobile_naver_map&output=json";
$html = file_get_contents($url);
//Json to array
$json = json_decode($html, true);
$result = $json["result"];
/**
upDirection
**/
$upDirection = $result["upDirection"];
$upDirection = utf8_encode($upDirection);
// Return as json
$return_json = [
"upDirection" => $upDirection
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($return_json);
//}
?>
And here is the code in swift
func fetchTimeSchedule() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// Send the station ID to PHP
var url: NSURL = NSURL(string: self.timeScheduleUrl)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
// Prepare post data
// station id
let stationId = self.currentViewingStation.id
// datetime
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let year = components.year
let month = components.month < 10 ? "0\(components.month)" : "\(components.month)"
let day = components.day < 10 ? "0\(components.day)" : "\(components.day)"
let hour = components.hour < 10 ? "0\(components.hour)" : "\(components.hour)"
let minutes = components.minute < 10 ? "0\(components.minute)" : "\(components.minute)"
let dateTime = "\(year)\(month)\(day)\(hour)\(minutes)"
var bodyData = "stationId=\(stationId)&dateTime=\(dateTime)"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
println("bodyData:\(bodyData)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error = \(error)")
return
}
if let HTTPresponse = response as? NSHTTPURLResponse {
println("received:\(HTTPresponse.statusCode)")
if HTTPresponse.statusCode == 200 { // Successfully got response
var err: NSError?
if let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) {
// decode json
println(json) // <- Here ******************
}
}
}
}
task.resume()
})
}
This is what the line
println(json) // <- Here ******************
prints out:
Optional({
upDirection = "";
})
i solved this problem with this code:
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 = "user=mike"
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)
println("API Response: \(results)")
With this php
header('Content-Type: application/json; charset=utf-8');
$a1 = $_POST['user'];
$returnValue = array("a1"=>$a1);
echo json_encode($returnValue);