无法通过HTTP请求发布到php,但代码中没有错误

时间:2016-10-20 05:29:28

标签: ios swift nsurlsession

尝试将文本输入发布到HTML页面中的PHP脚本。 iOS中没有错误,PHP可以成功发布到SQL数据库。出于某种原因,iOS无法成功将值传递给php脚本。

@IBOutlet weak var header: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    //helps the return button work
    self.txt1.delegate = self
    self.txt2.delegate = self
    self.txt3.delegate = self
    self.txt4.delegate = self
    self.txt5.delegate = self
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//Text Boxes
@IBOutlet weak var txt1: UITextField!
@IBOutlet weak var txt2: UITextField!
@IBOutlet weak var txt3: UITextField!
@IBOutlet weak var txt4: UITextField!
@IBOutlet weak var txt5: UITextField!

//function to make return button work..
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    txt1.resignFirstResponder()
    txt2.resignFirstResponder()
    txt3.resignFirstResponder()
    txt4.resignFirstResponder()
    txt5.resignFirstResponder()
    return true
}

//button action

@IBAction func Submit(_ sender: AnyObject) {
    let requestURL = URL(string: "*****")

    //You should use `URLRequest` in Swift 3, mutability is represented by `var`
    var request = URLRequest(url:requestURL!)

    request.httpMethod = "POST"

    //UITextField.text can be nil, you should treat nil cases
    //(Generally avoid using forced unwrapping `!` as far as you can.)
    let song = txt1.text ?? ""
    let artist = txt2.text ?? ""
    let album = txt3.text ?? ""
    let year = txt4.text ?? ""
    let genre = txt5.text ?? ""

    //`song`,... are all Strings, you have no need to add `as String`
    let songPost = "song=" + song
    let artistPost = "&artist=" + artist
    let albumPost = "&album=" + album
    let yearPost = "&year=" + year
    let genrePost = "&genre=" + genre

    //You need to make a single data containing all params
    //(Creating a concatenated String and getting `data` later would be another way.)
    var data = Data()
    data.append(songPost.data(using: String.Encoding.utf8)!)
    data.append(artistPost.data(using: String.Encoding.utf8)!)
    data.append(albumPost.data(using: String.Encoding.utf8)!)
    data.append(yearPost.data(using: String.Encoding.utf8)!)
    data.append(genrePost.data(using: String.Encoding.utf8)!)
    request.httpBody = data
    let task =  URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            print(response)

            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        //print response
        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()

控制台会发出一条非常大的消息,但它说状态代码应为200,但是为412。

我是否遗漏了一段可以点击HTML页面上的提交按钮的代码?

这是PHP脚本:

    <html>

   <head>
    <title>Information Gathered</title>
</head>

<body>

    <?php 

    echo "<p>Data Processed!</p>";

    $song = $_POST['song'];
    $artist = $_POST['artist'];
    $album = $_POST['album'];       
    $year = $_POST['year'];
    $genre = $_POST['genre'];

    echo $song . "</br>";
    echo $artist . "</br>";
    echo $album . "</br>";
    echo $year . "</br>";
    echo $genre . "</br>";

    DEFINE ('DB_USER', '****');
    DEFINE ('DB_PASSWORD', '****');
    DEFINE ('DB_HOST', '****');
    DEFINE ('DB_NAME', '****');

    $dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
    OR die('Could not connect to MySQL: ' .
    mysqli_connect_error());

    $sql = "insert into music (song, artist, album, year genre)
            values('$song', '$artist', '$album', '$year', '$genre',)";
    $dbc->query($sql)
    echo "<p> Data Entered!!!</p>"

    ?>

</body>

1 个答案:

答案 0 :(得分:0)

确保您已在info.plist上允许http请求。否则你只能调用安全的API即。 HTTPS。

对于http调用,请在info.plist

上设置此项

add this row and item

412状态代码说明

412状态代码表示请求下的其中一个条件失败。在一个或多个Request-Header字段中指定的前提条件返回false。

为什么会发生

服务器不符合请求者提出请求的前提条件之一。即,请求的标头指定了关于不适用于所请求文件的可接受文件的信息。