如何使用swift发出HTTP Post请求

时间:2016-11-07 08:09:09

标签: ios swift

typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject {
    static let sharedInstance = RestApiManager()
    let baseURL = "http://api.randomuser.me/"
    func postUser(){}
    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()
    }
}

如何在ViewController中调用httppost方法postuser并将头文件+编码参数传递给它?

http://www.api.com/post/data?username=kr%209&password=12 我也需要在ehader中发送会话/ cookie / useragent。

2 个答案:

答案 0 :(得分:0)

request.setValue("Your Header value", forHTTPHeaderField: "Header-Key") //User-Agent for ex.

答案 1 :(得分:0)

请注意,该类有sharedInstance个静态属性?这是swift中singleton pattern的实现。这允许您按如下方式调用RestApiManager类的方法:

let postBody: [String: AnyObject] = [
    "username": "joe.bloggs",
    "password": "test1234"
]

RestApiManager.sharedInstance.makeHTTPPostRequest(path: "relative/url", body: postBody) { json, err in
    // Handle response here...
}

单例模式允许您从项目的任何位置调用类的sharedInstance实例。您不需要在viewController中创建API Manger的实例来使用它。