本文介绍了Alamofire接受和内容类型JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Swift中的Alamofire发出GET请求。我需要设置以下标题:
I'm trying to make a GET request with Alamofire in Swift. I need to set the following headers:
Content-Type: application/json Accept: application/json我可以破解它并直接指定请求的标题,但我想用它来做 ParameterEncoding ,如库中所示。到目前为止我有这个:
I could hack around it and do it directly specifying the headers for the request, but I want to do it with ParameterEncoding, as is suggested in the library. So far I have this:
Alamofire.request(.GET, url, encoding: .JSON) .validate() .responseJSON { (req, res, json, error) in if (error != nil) { NSLog("Error: \(error)") println(req) println(res) } else { NSLog("Success: \(url)") var json = JSON(json!) } }Content-Type 已设置,但不是接受。我该怎么做呢?
Content-Type is set, but not Accept. How can I do this properly?
推荐答案我最终使用 URLRequestConvertible github/Alamofire/Alamofire#urlrequestconvertible
enum Router: URLRequestConvertible { static let baseUrlString = "someUrl" case Get(url: String) var URLRequest: NSMutableURLRequest { let path: String = { switch self { case .Get(let url): return "/\(url)" } }() let URL = NSURL(string: Router.baseUrlString)! let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) // set header fields URLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") URLRequest.setValue("application/json", forHTTPHeaderField: "Accept") return URLRequest.0 } }然后只需:
Alamofire.request(Router.Get(url: "")) .validate() .responseJSON { (req, res, json, error) in if (error != nil) { NSLog("Error: \(error)") println(req) println(res) } else { NSLog("Success") var json = JSON(json!) NSLog("\(json)") } }另一种方法是为整个会话指定它,检查@ David上面的评论:
Another way to do it is to specify it for the whole session, check @David's comment above:
Alamofire.Manager.sharedInstance.session.configuration .HTTPAdditionalHeaders?.updateValue("application/json", forKey: "Accept")更多推荐
Alamofire接受和内容类型JSON
发布评论