简体   繁体   English

如何使用Swift进行HTTP发布请求

[英]How to make HTTP Post request using 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()
    }
}

How can I call the httppost method postuser in my ViewController and pass headers + encoded parameters to it? 如何在ViewController中调用httppost方法postuser并将标头+编码参数传递给它?

Like http://www.api.com/post/data?username=kr%209&password=12 I need to send a session/cookie/useragent in ehader as well. http://www.api.com/post/data?username=kr%209&password=12一样,我也需要在ehader中发送会话/ cookie / useragent。

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

Notice that there is a sharedInstance static property of the class? 注意, sharedInstance有一个sharedInstance静态属性吗? This is an implementation of the singleton pattern in swift. 这是单例模式的快速实现。 This allows you to call the methods of the RestApiManager class as follows: 这使您可以按以下方式调用RestApiManager类的方法:

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

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

The singleton pattern allows you to call the sharedInstance instance of the class from anywhere in the project. 单例模式允许您从项目中的任何位置调用类的sharedInstance实例。 You don't need to create an instance of the API Manger in your viewController to use it. 您无需在viewController中创建API Manger的实例即可使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM