我想用swift发送一个http请求到PHP服务器。我管理发送数据,并阅读服务器的响应。我只是想根据请求类型是存在于JSON请求用swift发送http请求
这里我的PHP服务器上做不同的动作是我的发送请求的方法:
func sendHttpRequests(data : Dictionary<String, AnyObject>) //-> NSDictionary
{
let url = NSURL (string : "http://aaa.bbb.ccc.ddd")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL : url)
let payload1 = "\"r\":\"login\""
request.HTTPMethod = "POST"
request.HTTPBody = payload1.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
if let httpResponse = response as? NSHTTPURLResponse {
let responseCode = httpResponse.statusCode
print("Request Status \(responseCode)")
}
do
{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
print("Json received \(json)")
if let currItem = json["myKey"] as? String
{
print(currItem)
}
}
catch
{
print("error: \(error)")
}
}
}
当我刚刚发回一个响应此PHP剧本我得到回应成功:
<?php
$arr = array("myKey" => "myValue");
echo json_encode($arr);
?>
相反,当我尝试这样的事:
<?php
$postVar = $_POST['r'];
if (!empty($postVar))
{
$arr = array("status" => "it's ok");
echo json_encode($arr);
}
else
{
$arr = array("status" => "something wrong");
echo json_encode($arr);
}
?>
我得到这个错误:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
lePath是什么? –
我只是用这个方法替换那个方法,但问题仍然存在 –
lePath是这个调用的一个参数,你可以忽略它。发布你的修改过的代码呢? – user3069232