如何在xcode 8 swift 3中将textfield值作为String类型传递?

时间:2017-01-10 02:51:31

标签: arrays json swift3 xcode8

我试图在xcode 8 swift 3中理解发布请求的过程。

我设法通过将值添加到" paramString"手动发布数据。

我的问题是,如果输入数据来自文本字段,如何传递数据?

我将其命名为 usernameTxt passwordTxt 。如何使用下面的代码将这些值传递给PHP MySQL?

如果视图控制器有多个文本字段输入到Web服务中,那么" paramString" 会是什么?

我的代码到目前为止

import UIKit
class ViewController: UIViewController {

    @IBOutlet var usernameTxt: UITextField!
    @IBOutlet var passwordTxt: UITextField!
    @IBOutlet var loginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBAction func sendData(_ sender: Any) {
        data_request("http://localhost/send.php")
    }
    func data_request(_ url:String)
    {
        let name   = usernameTxt.text
        let pass   = passwordTxt.text

        let url:NSURL       = NSURL(string: url)!
        let session         = URLSession.shared

        let request         = NSMutableURLRequest(url: url as URL)
        request.httpMethod  = "POST"

        let paramString     = "data=" + name! 
        // let paramString  = "data=" + name! + "data2=" + pass! //this line does not work 
        request.httpBody    = paramString.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)
            }
        }
        task.resume()
    }
}

3 个答案:

答案 0 :(得分:0)

usernameTxt.textpasswordTxt.text

答案 1 :(得分:0)

POST请求的参数字符串必须采用格式

key1=value&key2=value2

创建字符串的便捷方法是String Interpolation

let paramString = "data=\(name)&data2=\(pass)"

检查text属性是否nil并且不是空的,这是一个很好的编程习惯。进一步在Swift 3中使用原生结构URLURLRequest

顺便说一句,Swift不是PHP。命名约定是使用驼峰案例。

...
@IBAction func sendData(_ sender: AnyObject) {
    dataRequest("http://localhost/send.php")
}

func dataRequest(_ url:String)
{
    guard let name = usernameTxt.text, !name.isEmpty,
        let pass = passwordTxt.text, !pass.isEmpty else { return }

    let url = URL(string: url)!
    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let paramString = "data=\(name)&data2=\(pass)"
    request.httpBody = paramString.data(using: .utf8)

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

        guard error == nil else {
            print("Error: ", error!)
            return
        }

        if let dataString = String(data: data!, encoding: .utf8) {
            print(dataString)
        }
    }
    task.resume()
}

答案 2 :(得分:-1)

        You can try this code for api request with parameter
          let user_id = 1
          let name = 'test'
        let post:NSString = "id=\(user_id)&name=\(name)" as NSString
                    let url:URL = URL(string:"ADD YOUR URL HERE")!
                    let postData:Data = post.data(using: String.Encoding.ascii.rawValue)!
                    let postLength:NSString = String( postData.count ) as NSString

                    let request:NSMutableURLRequest = NSMutableURLRequest(url: url)
                    request.httpMethod = "POST"
                    request.httpBody = postData
                    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
                    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                    request.setValue("application/json", forHTTPHeaderField: "Accept")

                    var reponseError: NSError?
                    var response: URLResponse?

                    var urlData: Data?
                    do {
                        urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)
                    } catch let error as NSError {
                        reponseError = error
                        urlData = nil
                    }

                    if ( urlData != nil ) {
                        let res = response as! HTTPURLResponse!;

                        if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
                        {}

    }