Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

swift 3 posting data

erdinc27erdinc27 TurkeyPosts: 396 @ @
i am developing an application first time by using swift 3. But i am having trouble with sending data with post method. My php script works well when i call it with postman but when i try to send data from swift then i got response with "Empty parameters" which i coded like that in PHP script. Here is my code.
func loginWithDictionary (paramDictionary:[String : String], completionHandler:@escaping (_ response : NSDictionary) -> Void) {
        
        let urlString = "webservice/url/path"
        
        //create the url with NSURL
        let url = NSURL(string: urlString)
        
        //create the session object
        //let session = URLSession.shared
        let config = URLSessionConfiguration.default // Session Configuration
        let session = URLSession(configuration: config) // Load configuration into Session
        
        //now create the NSMutableRequest object using the url object
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "POST" //set http method as POST
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: paramDictionary, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
            
        } catch let error {
            print(error.localizedDescription)
        }
        
        //HTTP Headers
        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: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary {
                    // handle json...
                    completionHandler(json)
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }

What is the problem here ?
Sign In or Register to comment.