Xcode 8 Swift 3.0:解析错误 - 无法读取 PHPMailer 代码

Xcode 8 Swift 3.0 : Parse error - Could not read PHPMailer code

我在 xcode 8 上有问题。

在 PHP 中,我正在使用 PHPMailer 发送电子邮件。我的 PHP 代码如下。

send.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('sender@mail.com', 'sender');  
            $mail->addAddress('receiver@mail.com','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。它说:

Parse error: The data couldn’t be read because it isn’t in the correct format.

Xcode 无法读取 PHP 文件中的 PHPMailer 代码,导致我的 swift 3.0 代码执行 Catch 语句而不是 message == '1' 语句。我的 swift 代码如下。

post.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';
}

它没有 return JSON 代码,所以您在解析它时遇到问题我并不感到惊讶。你之前发布过这个问题,但它很不清楚 - 你听起来像 Xcode 无法打开你的 PHP 文件,而不是你无法解析响应;这是一个 Swift 运行时错误,而不是 Xcode 错误。

Return 您的回复格式为 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'
    ]);
}