JSON请求发送空数据(swift)

时间:2017-12-29 15:54:09

标签: php ios json swift xcode

我的iOS应用程序正在向Web服务发送空数据。我花了几个小时才找到解决方案但没有任何效果。 应用程序应该通过PHP脚本向数据库发送一个kontrah号码。然后数据库必须识别是否可以在数据库中找到kontrah数。然后,如果数字正确,我将从数据库服务器获取请求。问题是我发送的号码肯定是正确的。我查看了发送到数据库的内容,它全部为空:

{"kontrah":null,"telefon":null,"opis":null,"afakt":null}

我已经使用Java制作了相同的应用程序,但是在Android Studio中安装了Android,一切正常。

我的代码:

@IBAction func submitAction(_ sender: AnyObject) {
    let kontrah: String = fkontrah.text!
     let telefon: String = ftelefon.text!



    let json = [ "kontrah" : (kontrah), "telefon" : (telefon), "opis" : (selectedvalue), "afakt" : (selectedafakt)  ]

    print (json)

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
        print(jsonData)
        // create post request
        let url = NSURL(string: "http://hetman.pl/ios/post2.php")!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        // insert json data to the request
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData



        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            if error != nil{
                return
            }

            do {
                let t  = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                print(t)

            } catch {
                print("Error  43-> \(error)")
            }
        }
        let alert = UIAlertController(title: "Wysłano poprawnie", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)


        task.resume()


    }

    catch {
        //handle error. Probably return or mark function as throws
        print(error)
        return
    }
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return(true)
}

}

日志:

2017-12-29 15:59:43.867463+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1ad829e00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:47.717492+0100 Hetman4[10692:4029622] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/bartoszlucinski/Library/Developer/CoreSimulator/Devices/3BE9103E-97CA-4E0B-AE53-6196EE08C49D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-12-29 15:59:47.717874+0100 Hetman4[10692:4029622] [MC] Reading from private effective user settings.
2017-12-29 15:59:52.225804+0100 Hetman4[10692:4029622] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 4072550144015629828_PortraitChoco_iPhone-Simple-Pad_Default
["telefon": "510356448", "kontrah": "1400-685", "opis": "Świnia", "afakt": "0"]
94 bytes
2017-12-29 15:59:57.074868+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1b0096400> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:57.628832+0100 Hetman4[10692:4029622] Presenting view controllers on detached view controllers is discouraged <Hetman4.ViewController: 0x7fa1ac428ef0>.
Optional(["error": <null>, "result": kontrah  doesn't exist, "unAuthorizedRequest": 0, "success": 1])

PHP脚本:

<?php
$kontrah = urlencode($_POST['kontrah']);
$telefon = urlencode($_POST['telefon']);
$opis = urlencode($_POST['opis']);
$afakt = urlencode($_POST['afakt']);

$url = 'https://hetman.e4b.com.pl/api/services/app/zlecenie/FormAddZlecenie?kontrah='.$kontrah.'&telefon='.$telefon.'&opis='.$opis.'&afakt='.&afakt;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);


$results = curl_exec($ch);

curl_close($ch);
?>

1 个答案:

答案 0 :(得分:0)

有几个问题:

  1. 您的服务器期待sapply(df,function(x)sum(x[x>1]-1)) colA colB colC colD 1 2 3 4 请求,而不是JSON请求。响应是JSON,但请求不是。

  2. 当我使用application/x-www-form-urlencoded网址时,它会重定向到hetman.pl,但会将www.hetman.pl替换为POST。当我直接向GET发送请求时,我收到了不同的消息。但是,我无法阅读它们,所以我无法评论这是好还是坏。

  3. 与手头的问题无关,Swift代码可以整理一下,分别用www.hetman.plNSURL取代NSURLRequestURL

  4. 将它们拉到一起,就会得到类似的结果:

    URLRequest

    其中

    let parameters = ["kontrah" : kontrah, "telefon" : telefon, "opis" : selectedvalue, "afakt" : selectedafakt]
    
    let url = URL(string: "http://www.hetman.pl/ios/post2.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.setBodyContent(parameters)
    
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error ?? "Unknown error")
            return
        }
    
        do {
            let t  = try JSONSerialization.jsonObject(with: data) as? [String:AnyObject]
            print(t ?? "Invalid")
        } catch {
            print("Error  43-> \(error)")
        }
    }
    task.resume()