执行简单的POST请求Swift

时间:2016-03-05 20:27:54

标签: ios swift curl http-post

我想用Swift执行一些小的POST请求,但我不知道怎么做。这就是我用CURL做的方式:

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

如何在Swift for iOS中执行此操作?

2 个答案:

答案 0 :(得分:2)

非常简单的RestApiManager类我觉得它会对你有所帮助

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()
    }

}

答案 1 :(得分:0)

然而,typedef的回答非常好,实际上应该是这样的简单代码:

    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()


    } 

}

此处的关键是let postString = "yourStringToPost".dataUsingEncoding(NSUTF8StringEncoding)