HTTP Request in Swift with POST method

前端 未结 7 909
名媛妹妹
名媛妹妹 2020-11-22 05:46

I\'m trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.

Example:

Link: www.thisismylink.com/postName.php

Params:

7条回答
  •  [愿得一人]
    2020-11-22 06:18

    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 = ["id": 13, "name": "jack"]
    
        //create the url with URL
        let url = URL(string: "www.thisismylink.com/postName.php")! //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 as URLRequest, 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()
    }
    

提交回复
热议问题