我在 xcode 8 上有问题。
在 PHP 中,我使用 PHPMailer 发送电子邮件。我的 PHP 代码如下。
发送.php
<?php
require 'database/connect.php';
global $connect;
date_default_timezone_set('Etc/UTC');
require 'PHPMailer-master2/PHPMailerAutoload.php';
if ( isset($_POST['data1']) && isset($_POST['data2']))
{
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$sql = "SELECT * FROM table WHERE data1 = '$data1' AND data2='$data2'";
$result = mysqli_query($connect, $sql);
if ($result && mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result)){
}
$output = array('message' => '1');
echo json_encode($output);
$add = "INSERT INTO table (data1, data2)
VALUES ('$data1','$data2')
";
$run = mysqli_query($connect,$add);
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'gmail.com';
$mail->Password = '******';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'sender');
$mail->addAddress('[email protected]','receiver');
$mail->isHTML(true);
$mail->Subject = 'Test';
$mail->Body = 'Test';
$mail->AltBody = 'Test';
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
$status = array();
$status[] = array('status' => '1');
}
$output = array('message' => '1', 'status' => $status);
echo json_encode($output);
exit();
// End sending email
exit();
mysqli_free_result($result);
}
else {}
}
?>
我设法使用上面的代码将数据发送到服务器并发送电子邮件给接收者。
我现在面临的唯一问题是在 xcode 中。它说:
解析错误:无法读取数据,因为它的格式不正确。
Xcode 无法读取 PHP 文件中的 PHPMailer 代码,这导致我的 swift 3.0 代码执行Catch语句而不是message == '1'语句。我的快速代码如下。
后.swift
@IBAction func sendApplyMovement(_ sender: Any) {
let url = URL(string: "http://localhost/send.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let valueToSend = "data1=&data2"
request.httpBody = valueToSend.data(using: String.Encoding.utf8)
let myAlert = UIAlertController(title: "Confirm", message: "Sure ?", preferredStyle: UIAlertControllerStyle.alert)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)
let okaction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler:
{
action in
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async {
let message = Int(json["message"]!)
let status = Int(json["status"]!)
if(message == 1){
if(status == 1){
print("Success")
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let navigationController = UINavigationController.init(rootViewController: myViewController)
appDelegate.window?.rootViewController = navigationController
appDelegate.window?.makeKeyAndVisible()
let myAlert = UIAlertController(title: "Success!", message: "Sent !", preferredStyle: UIAlertControllerStyle.alert)
myAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
navigationController.present(myAlert, animated: true, completion: nil)
return
}
}
else {return}
}
}
}
catch let parseError { print("Parse error: \(parseError.localizedDescription)") }
}
})
task.resume()
}
)
myAlert.addAction(okaction)
myAlert.addAction(cancel)
self.present(myAlert, animated: true, completion: nil)
}
}
有什么我需要修改才能使它工作的吗?
你这样做:
if let json = try JSONSerialization.jsonObject(with: data!)
这意味着您获得的数据是 JSON 格式,但您的 PHPMailer 代码是这样做的:
if(!$mail->send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent';
}
它不返回 JSON 代码,因此您在解析它时遇到问题我并不感到惊讶。你之前发布过这个问题,但它很不清楚 - 你让它听起来像是 Xcode 无法打开你的 PHP 文件,而不是你无法解析响应;这是 Swift 运行时错误,而不是 Xcode 错误。
以 JSON 格式返回您的响应,您可能会获得更多成功,例如:
if(!$mail->send()) {
echo json_encode([
'status' => false,
'message' => 'Message could not be sent. Error: ' . $mail->ErrorInfo
]);
} else {
echo json_encode([
'status' => true,
'message' => 'Message sent'
]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句