2017-04-10 1 views
0

를 읽을 수 없습니다. 내 PHP 코드는 아래와 같습니다.엑스 코드 8 스위프트 3.0 : 구문 분석 오류 - 내가 이메일을 보내 PHPMailer를 사용하고, PHP에서 엑스 코드 (8)</p> <p>에 문제가 PHPMailer 코드

<?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 {} 
    } 
?> 

send.php 나는 서버로 데이터를 전송하고 위의 코드를 사용하여 수신기 이메일을 보낼 수 있었다.

현재 제가 당면한 유일한 문제는 xcode입니다. 그것은 말한다 :

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

enter image description here

엑스 코드, 즉 == 내 SWIFT 3.0 코드 대신 메시지의 캐치 문을 실행하게 '1'를 PHP 파일 내 PHPMailer 코드를 읽을 수 없습니다 성명서. 내 신속한 코드는 아래와 같습니다. 나는 그것이 작동하도록하기 위해 수정해야 할 일이

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) 
     } 
    } 

있습니까? 당신은이 일을하고

답변

1

:

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 파일을 열 수 없으며 응답을 구문 분석 할 수 없다는 소리를 내었습니다. 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' 
    ]); 
} 
+0

확인합니다. 나는 그것을 먼저 시도 할 것이다. . . – AlotJai

+0

"Parse error"오류가 발생했지만 여전히 메시지 내부에서 UIAlert를 실행할 수 없습니다. == 1 – AlotJai

+0

그냥 코드를 읽습니다. 'message'요소에서 '1'값을 찾고 있는데 거기에 문자열을 넣었습니다. 출력과 입력 라인을 확실히 할 필요가있다. 코드를'if (json [ "status"])'로 바꿔보십시오. 대신'status' 엘리먼트를 볼 것입니다. – Synchro