我正在尝试使用Alamofire在我的swift应用程序中发送一个PHP Post请求,该应用程序必须使用OVH api发送短信,但我遇到了一个问题:
FAILURE: Error Domain=com.alamofire.error Code=-6006 "JSON could not be serialized. Input data was nil or zero length." UserInfo={NSLocalizedFailureReason=JSON could not be serialized. Input data was nil or zero length.}
我没有找到如何从PHP脚本中看到回声来解决它。我认为这不是Alamofire的问题,因为我提出了另一个发送电子邮件的请求,而且效果很好。这是我的请求,其中有错误:
func sendSmsAutoRequest(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
let prefs = NSUserDefaults.standardUserDefaults()
let username = prefs.stringForKey(StorageManager.USER_NAME)!
let messageText = prefs.stringForKey(StorageManager.MESSAGE_TEXT)!
let parameters = ["contactsSms": contactsSms, "username": username, "messageText": messageText]
request(.POST, "http://XXX/dontworry/sendAutoSms.php", parameters: (parameters as! [String : AnyObject])).responseJSON { response in
print(response)
}
}
这是我的剧本:
<?php
require __DIR__ . '/vendor/autoload.php';
use \Ovh\Api;
$applicationKey = "XXX";
$applicationSecret = "XXX";
$consumer_key = "XXX";
$endpoint = "ovh-eu";
$contactsSms = $_POST['contactsSms'];
$userName = $_POST['username'];
$messageText = $_POST['messageText'];
$conn = new Api($applicationKey,
$applicationSecret,
$endpoint,
$consumer_key);
$smsServices = $conn->get('/sms/');
$content = (object) array(
"charset"=> "UTF-8",
"class"=> "phoneDisplay",
"coding"=> "7bit",
"message"=> $messageText,
"noStopClause"=> true,
"priority"=> "high",
"receivers"=> $contactsSms,
"senderForResponse"=> true,
"validityPeriod"=> 2880
);
$resultPostJob = $conn->post('/sms/'. $smsServices[0] . '/jobs/', $content);
$smsJobs = $conn->get('/sms/'. $smsServices[0] . '/jobs/');
echo '{"contacts": $contactsSms,"username": $username, "messageText": $messageText, "result": $resultPostJob, "sms": $smsJobs}'; ?>
编辑:它似乎工作,我没有错误了!但短信没有发送......
答案 0 :(得分:3)
从第一次阅读开始,您的PHP脚本很可能会打印出无效的JSON。以下语句将打印包含不带引号的字符串的JSON(假设一个或多个参数如$_POST['messsageText']
包含字符串值):
echo '{"contacts": $contactsSms,"username": $username, "messageText": $messageText, "result": $resultPostJob, "sms": $smsJobs}';
示例输出(为便于阅读而打印漂亮):
{
"contacts": foobar, # <-- This is invalid! It's a string and needs to be quoted!
"username": johndoe,
"messageText": Hello World, # <-- This is even more invalid!
...
}
我建议依靠PHP的json_encode
函数来生成有效的JSON输出:
echo json_encode([
"contacts" => $contactsSms,
"username" => $username,
"messageText" => $messageText,
// etc.
]);
答案 1 :(得分:1)
这是alamoFire中的一个错误,已在3.1.1版本中修复,请参阅pull #889,修复版仅在您的REST服务返回响应204(NO_RESPONSE)时才有效,这在理论上是正确的这样做的方法。
答案 2 :(得分:0)
序列化是将对象转换为JSON字符串的过程。所以问题不在于您的回复处理,而在于您的回复。
记录parameters
字典的内容,并检查是否为nil值。