如何删除使用Swift 3.0在PHP MySQL数据库中添加的Optional("")字符串?

时间:2017-01-16 08:17:16

标签: json swift3 xcode8

我使用的是Swift 3.0,我希望将数据从X Code 8发布到mysql数据库中。

我可以在x代码中打印该值并删除Optional(""),但是当它发送到mysql数据库时,仍然添加了Optional("")字符串。 / p>

我相信我在这行代码上遇到了问题。我的问题是如何发布没有可选的值("")?

var d1: String!
var d2: String!
d1 = _data1.text
d2 = _data2.text

let paramToSend     = "data1=\(d1)&data2=\(d2)"

这是我的 ViewController.swift

import UIKit
class ViewController: UIViewController {
    @IBOutlet var _data1: UITextField!
    @IBOutlet var _data2: UITextField!
    @IBOutlet var _send_button: UIButton!
    var d1: String!
    var d2: String!
    override func viewDidLoad() {
        super.viewDidLoad(
    }
    @IBAction func sendData(_ sender: Any) {
        d1 = _data1.text
        d2 = _data2.text
        if (d1 == "" || d2 == "") {
            return
        }
        else {
            let url             = URL(string: "http://localhost/send.php")
            let session         = URLSession.shared
            let request         = NSMutableURLRequest(url: url! as URL)
            request.httpMethod  = "POST"

            let paramToSend     = "data1=\(d1)&data2=\(d2)"
            request.httpBody    = paramToSend.data(using: String.Encoding.utf8)

            let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
                guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
                    print("Error")
                    return
                }
                if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
                    print(dataString)
                    let newdata1: String? = d1
                    let newdata2: String? = d2
                    print(newdata1!)
                    print(newdata2!)
                }
            }
            task.resume()
        }
    }
}

1 个答案:

答案 0 :(得分:3)

首先,如果可能,请不要将变量声明为可选项:

var d1: String = ""
var d2: String = ""

d1 = _data1.text ?? ""
d2 = _data2.text ?? ""