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並將頭文件+編碼參數傳遞給它?如何使用swift進行HTTP POST請求
Like http://www.api.com/post/data?username=kr%209&password=12 我需要在ehader中發送會話/ cookie/useragent。
request.allHTTPHeaderFields = [ 「內容類型」: 「應用/ JSON」, 「接受」: 「應用/ JSON」 ] request.addValue(mySessionToken,forHTTPHeaderField: 「SessionToken」) – jpulikkottil
當然,你可以做到這一點。如果你設法寫出你上面寫的代碼,那事情會非常簡單。只需爲需要的方法添加額外的參數,然後構建請求。 – EridB