这是我启动http请求的方式:
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)")
}
在我的php文件中,我有
public function check()
{
if($this->input->post('email')) {
echo json_encode("YES");
} else {
echo json_encode("NO");
}
}
它总是让我“不”。有人知道为什么吗?
答案 0 :(得分:2)
<强>您好。解决。强>
这取决于您发送数据的方式。在我的情况下,它是原始的,只说请求正文。
所以你需要做一些事情:
$data = json_decode(file_get_contents('php://input'));
,数据将是包含帖子值的数组。
答案 1 :(得分:0)
尝试使用:
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
}
在你的php文件中尝试使用:$_POST['email']
而非$ this-&gt; input-&gt; post('email')