php - 从 Swift 3 iOS 调用 Php

标签 php ios swift xcode swift3

您好,我已经在新版本的 swift 3 中更新了我的旧 swift 应用程序,自从我将应用程序更新到 swift 3 xcode me 以来,代码通过在 post 中传递值然后返回 json 消息连接到 php 页面出现以下错误,我该如何修复这些错误?

错误:

enter image description here

Swift 代码:

let URL_SAVE_TEAM = "http://localhost/ios-login.php"
    var email:String = "";
    var password:String = "";


    func PrintValue(){

       // print(username);
        //print(password);
    }

    func Login() -> Bool{


        //created NSURL
        let requestURL = NSURL(string: URL_SAVE_TEAM)

        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(URL: requestURL)

        //setting the method to post
        request.HTTPMethod = "POST"

        //getting values from text fields


        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "email="+email+"&password="+password;

        //adding the parameters to request body
        request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)


        //creating a task to send the post request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in

            if error != nil{
                print("error is \(error)")
                return;
            }

            //parsing the response
            do {
                //converting resonse to NSDictionary
                let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                //parsing the json
                if let parseJSON = myJSON {

                    //creating a string
                    var msg : String!

                    //getting the json response
                    msg = parseJSON["message"] as! String?

                    //printing the response
                    print(msg)



                }
            } catch {
                print(error)
            }

        }
        //executing the task
        task.resume()

        return false;
    }

错误的 Xcode 图像:

enter image description here

PHP 代码:

<?php

    header('Content-Type: application/json');
    $email= $_POST['email'];
    $password = $_POST['password'];
    $ris='Ti rispondo dal server zio';

   echo json_encode($ris);
  //  echo "prova";

?>

最佳答案

我会写得更快:)

func Login() -> Bool{

//created URL
guard let requestURL = URL(string: URL_SAVE_TEAM) else { return false }

//creating URLRequest
var request = URLRequest(url: requestURL)

//setting the method to post
request.httpMethod = "POST"

//getting values from text fields


//creating the post parameter by concatenating the keys and values from text field
let postParameters = "email=\(email)&password=\(password)"

//adding the parameters to request body
request.httpBody = postParameters.data(using: .utf8)

//creating a task to send the post request
let session = URLSession.shared

let task = session.dataTask(with: request) {
  data, response, error in

  guard error == nil else {
    print("error is \(error!.localizedDescription)")
    return
  }

  guard let data = data else {
    print("No data was returned by the request!")
    return
  }

  //parsing the response
  do {
    //converting resonse to NSDictionary
    let myJSON =  try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<String, String?>

    //parsing the json
    guard let parseJSON = myJSON, let msg = parseJSON["message"] as? String else {
      print("Error parsing data")
      return
    }

    //printing the response
    print(msg)

  } catch {
    print(error)
  }

}

//executing the task
task.resume()

return false

}

您可能会考虑在函数中添加一个完成处理程序来处理登录成功!

关于php - 从 Swift 3 iOS 调用 Php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44077590/

相关文章:

php - 如何使用未知数量的参数创建准备好的语句? (对于搜索框)

ios - 在 Swift 中使用 NSNumber numberWithBool

ios - 在 Swift 中的 UITextView 上放置阴影

ios - Swift - 遍历字符串中的字符导致内存泄漏

swift - 根据 IF 语句更改 ViewController

javascript - Laravel PHP 验证对比JavaScript 验证

php - 使用 WHERE 语句在循环中 INSERT INTO 表(以填充外键列)

php - Magento:所有页面都会永远加载

ios - 快速获取点击的 ImageView

ios - 无法将 UIImageView 放入 SKScene 的 View 中