简体   繁体   中英

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?

Like http://www.api.com/post/data?username=kr%209&password=12 I need to send a session/cookie/useragent in ehader as well.

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

Notice that there is a sharedInstance static property of the class? This is an implementation of the singleton pattern in swift. This allows you to call the methods of the RestApiManager class as follows:

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. You don't need to create an instance of the API Manger in your viewController to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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