Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire Accept and Content-Type JSON

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

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 is set, but not Accept. How can I do this properly?

like image 225
jlhonora Avatar asked Feb 06 '15 20:02

jlhonora


1 Answers

I ended up using URLRequestConvertible https://github.com/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
    }
}

And then just:

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)")
        }
}

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")
like image 69
jlhonora Avatar answered Oct 11 '22 17:10

jlhonora