10

I'm new to IOS development and I have started with the swift language.

I'm trying to get the value from two text fields and convert those two text fields into json and send that json to the server receive.php.

lets concider that tow text fields are - name - pass

how do i create a Json & send that to server when a button is clicked ?

2
  • 1
    possible duplicate of How to make an HTTP request in Swift? Commented Dec 26, 2014 at 8:33
  • 2
    But how to create & send Json is not there in it. Commented Dec 26, 2014 at 8:39

3 Answers 3

29

By using http POST method with URLSession. Let's say you are calling submitAction method on the press of the login button

Swift 4 and above

@IBAction func submitAction(_ sender: UIButton) {
    
    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

    let parameters: [String: String] = ["name": nametextField.text, "password": passwordTextField.text]
    
    //create the url with URL
    let url = URL(string: "http://myServerName.com/api")! //change the url
    
    //create the session object
    let session = URLSession.shared
    
    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
        
    } catch let error {
        print(error.localizedDescription)
    }
    
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    
    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in
        
        guard error == nil else {
            return
        }
        
        guard let data = data else {
            return
        }
        
        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }
            
        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is it similar for Swift 5? Also, if the server required a password, where would that go in the code?
yes works with swift 5
1

Swift 3,Swift 4 The method above is very in-efficient, use alamofire instead

https://github.com/Alamofire/Alamofire

get email and passwoord from textfield

@IBAction func submitAction(sender: AnyObject) {
let email= emailfield.text
let password= emailfield.text
let parameters: Parameters = [
    "email": email,
    "password": password
    ]

Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) }

or here is an example

let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
    "x": 1,
    "y": 2,
    "z": 3
]
]

// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3

Comments

1

For those having issues getting Alamofire.request to work, use AF instead of Alamofire. For example:

AF.request("https://httpbin.org/post", method: .post, parameters: parameters)

From the docs:

Previous versions of Alamofire's documentation used examples like Alamofire.request(). This API, while it appeared to require the Alamofire prefix, in fact worked fine without it. The request method and other functions were available globally in any file with import Alamofire. Starting in Alamofire 5, this functionality has been removed and instead the AF global is a reference to Session.default. This allows Alamofire to offer the same convenience functionality while not having to pollute the global namespace every time Alamofire is used and not having to duplicate the Session API globally. Similarly, types extended by Alamofire will use an af property extension to separate the functionality Alamofire adds from other extensions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.