Reputation: 453
This is the way I launch the http request :
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": UIDevice.currentDevice().model]
let session = NSURLSession(configuration: config)
var request = NSMutableURLRequest(URL: NSURL(string: "http://WWWW/login/check"))
request.HTTPMethod = "POST"
let valuesToSend = ["email": self.email!, "password": self.password!]
var error: NSError?
let data = NSJSONSerialization.dataWithJSONObject(valuesToSend, options:NSJSONWritingOptions.PrettyPrinted, error: &error)
var err: NSErrorPointer?
if error == nil {
let task = session.uploadTaskWithRequest(request, fromData: data, completionHandler: {data, response, error in
if error == nil {
println("DATA == \(NSString(data: data, encoding: NSUTF8StringEncoding))")
println("response == \(response)")
}
})
task.resume()
} else {
println("Oups error \(error)")
}
And in my php file, I have
public function check()
{
if($this->input->post('email')) {
echo json_encode("YES");
} else {
echo json_encode("NO");
}
}
It always return me "NO". Someone know why ?
Upvotes: 1
Views: 613
Reputation: 453
Hi. Resolved.
It depends how you send your data. In my case, it was raw, that's say only with the request body.
So you need to do something like :
$data = json_decode(file_get_contents('php://input'));
and data will be an array with your post values.
Upvotes: 2
Reputation: 5187
Try using this:
func JSONParseArray(jsonString: String) -> Array<String> {
var e: NSError?
var data: NSData!=jsonString.dataUsingEncoding(NSUTF8StringEncoding)
var jsonObj = NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions(0),
error: &e) as Array<String>
if e == 0 {
return Array<String>()
} else {
return jsonObj
}
}
var bodyData = "email=" + email + "&password=" + password //Post data
let URL: NSURL = NSURL(string: "URL to php file")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
var output = NSString(data: data, encoding: NSUTF8StringEncoding) //Get the output
var array = self.JSONParseArray(self.output) //The output but in a array
}
And in you php file try using: $_POST['email']
and not $this->input->post('email')
Upvotes: 0