How to pass textfield value as String type in xcod

2019-09-13 23:14发布

I'm trying to understand the process of post request in xcode 8 swift 3.

I managed to post data manually by adding value into "paramString".

My question is, how to pass the data if the input data is coming from textfield?

I named it usernameTxt and passwordTxt. How to pass these value into PHP MySQL using the code below?

What would "paramString" will be if the view controller have multiple textfield input into web services?

My code so far as below

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条回答
狗以群分
2楼-- · 2019-09-13 23:49

usernameTxt.text and passwordTxt.text

查看更多
劫难
3楼-- · 2019-09-13 23:59

A parameter string for a POST request must be in format

key1=value&key2=value2

A convenient way to create the string is String Interpolation

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

It's good programming habit to check if the text properties are not nil and not empty. Further in Swift 3 use the native structs URL and URLRequest.

By the way Swift is not PHP. The naming convention is to use camel case.

...
@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()
}
查看更多
地球回转人心会变
4楼-- · 2019-09-13 23:59
        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)
                        {}

    } 
查看更多
登录 后发表回答