我为一个项目创建了一个函数,使用正确的参数,您可以发布、放置和获取
private func fetchData(feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:(success:Bool,data:NSDictionary?)->Void){
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: feed)
if let unwrapped_url = NSURL(string: feed){
let request = NSMutableURLRequest(URL: unwrapped_url)
if let tk = token {
let authValue = "Token \(tk)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")
}
if let parm = parameters{
if let data = NSJSONSerialization.dataWithJSONObject(parm, options:NSJSONWritingOptions(0), error:nil) as NSData? {
//println(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil))
request.HTTPBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
}
}
if let unwrapped_method = method {
request.HTTPMethod = unwrapped_method
}
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.timeoutIntervalForRequest = 15.0
let session = NSURLSession(configuration: sessionConfiguration)
let taskGetCategories = session.dataTaskWithRequest(request){ (responseData, response, error) -> Void in
let statusCode = (response as NSHTTPURLResponse?)?.statusCode
//println("Status Code: \(statusCode), error: \(error)")
if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
onCompletion(success: false, data:nil)
}
else {
var e: NSError?
if let dictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: .MutableContainers | .AllowFragments, error: &e) as? NSDictionary{
onCompletion(success:true,data:dictionary)
}
else{
onCompletion(success: false, data:nil)
}
}
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
taskGetCategories.resume()
}
}
}
以下是如何使用函数:
fetchData(feed,token: Constants.token(), parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
if success { //Code after completion} })
-
饲料->这是到服务器的链接
-
令牌(可选)->出于安全目的,某些请求需要令牌
-
参数(可选)->这些是您可以传递给服务器的所有参数。(顺便说一下,这是一本词典)
-
方法(可选)->在这里,您可以选择所需的请求类型(“GET”、“POST”、“PUT”)
-
完井关闭->这里传递一个函数,该函数将在请求完成时执行。在闭包中,您会得到两个参数:“success”是一个布尔值,表示请求是否成功,以及“data”。这是一个包含所有响应数据的字典。(可能为零)
希望我帮了忙。对不起我的英语