Dragos Strugar
Dragos Strugar

Reputation: 1644

Execute simple POST request Swift

I want to execute little POST request with Swift, but I don't know how to do it. This is how I do it with CURL:

curl --data "ime=YOURNAME&pitanje=YOURQUESTION" http://localhost/seka/postavi.php

How to do this in Swift for iOS?

Upvotes: 1

Views: 1066

Answers (2)

Dragos Strugar
Dragos Strugar

Reputation: 1644

However typedef's answer was really good, what actually worked as it should be is this simple code:

    func postRequest(text: String, ime: String) {
    if let url = NSURL(string: "your_link_to_post_to"){

        let request = NSMutableURLRequest(URL: url)!)
        request.HTTPMethod = "POST"
        let postString = "ime=\(ime)&pitanje=\(text)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()


    } 

}

The key here is let postString = "yourStringToPost".dataUsingEncoding(NSUTF8StringEncoding)

Upvotes: 0

typedef
typedef

Reputation: 937

very simple RestApiManager class i think it will help to you

typealias ServiceResponse = (JSON, NSError?) -> Void

class RestApiManager: NSObject {
    static let sharedInstance = RestApiManager()

    let baseURL = "http://api.randomuser.me/"

    func getRandomUser(onCompletion: (JSON) -> Void) {
        let route = baseURL
        makeHTTPGetRequest(route, onCompletion: { json, err in
            onCompletion(json as JSON)
        })
    }

    func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
        let request = NSMutableURLRequest(URL: NSURL(string: path)!)

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data)
            onCompletion(json, error)
        })
        task.resume()
    }

    func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
        var err: NSError?
        let request = NSMutableURLRequest(URL: NSURL(string: path)!)

        // Set the method to POST
        request.HTTPMethod = "POST"

        // Set the POST body for the request
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(body, options: nil, error: &err)
        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data)
            onCompletion(json, err)
        })
        task.resume()
    }

}

Upvotes: 2

Related Questions