jsonswiftxcode7ios9.3

How to send POST request with JSON data to external database for login app in IOS using Swift?


I am new in Swift and iOS. Please send me the sample code for POST request with JSON data to external database for login app in iOS using Swift


Solution

  • You can call post api like below code,

    Try this

    func callPostApi()
    {
        let baseUrl : NSString = NSString(format: "YOUR_BASE_URL")   //"http://at.webby.com/php.api"
        let request = NSMutableURLRequest(URL: NSURL(string: baseUrl as String)!)
        let session = NSURLSession.sharedSession()
    
        request.HTTPMethod = "POST"
        let stringPost = "username=test&password=12345" // Key and Value param as string
    
        let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
    
        request.timeoutInterval = 60
        request.HTTPBody=data
    
        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    
            let err1: NSError? = nil
            do
            {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                print(json)
            }
            catch
            {
                print(err1)
            }
        })
    
        task.resume()
    }
    

    Hope this will help you.