David David - 1 year ago 80
Swift Question

POST data while when getting JSON with SwiftyJSON

I'm developing an iOS app with Xcode and Swift.

I'm getting JSON data with SwiftyJSON.swift and the following code:

import UIKit

class ViewController: UIViewController {

var dict = NSDictionary()

@IBOutlet weak var firstLb: UILabel!
@IBOutlet weak var secondLb: UILabel!

override func viewDidLoad() {


let urlString = "http://example.com/showUserInfo.php"

if let url = NSURL(string: urlString) {

if let data = try? NSData(contentsOfURL: url, options: []) {

let json = JSON(data: data)


let f = json[0]["name"].stringValue

let s = json[0]["age"].stringValue

firstLb.text = f

secondLb.text = s

That works fine but I want to be able to post to my PHP script. (My PHP script is ready for it. It can receive POST data and handle it.)

I normally use the following code to POST data to PHP:

let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/showUserInfo.php")!)
request.HTTPMethod = "POST"
let postString = "username=MyUserName"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

That means: I know how to get data with JSON and I know how to POST a value to PHP. But unfortunately I'm not able to combine both.

Does anybody know how to combine them? How to POST a value to a PHP script where getting the JSON data?

Answer Source

To post data to Server you should use In-build APIs, or you can use a very famous library called : Alamofire

Sample Code:

    let params:[String:AnyObject] = [
        "foo" : 1,
        "bar" : 2

    request(.POST,  "URL", parameters: params)
        .responseJSON { response in

            switch response.result {
            case .Success(let JSON):
                print("JSON: \(JSON)")

            case .Failure(let error):
                print("Request failed with error: \(error)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download