Alamofire自定义标头无法正常工作

时间:2016-03-21 02:47:43

标签: swift alamofire

我正在尝试向Alamofire请求添加自定义标头,但我认为标头不被识别。我仍然收到相同的结果,现在收到App Transport security错误。我正在添加此处指定的标题 - > http://developer.dribbble.com/v1/media/#comment-body-property(删除html并仅返回文本)。这是我到目前为止所尝试过的。

 let headers = ["Accept": "application/vnd.dribbble.v1.text+json"]
        var manager: Manager = Manager.sharedInstance
        manager.session.configuration.HTTPAdditionalHeaders = headers

        manager.request(.GET, url, parameters: parameters).validate().responseJSON { response in
            switch response.result {
            case .Success:
                if let value = response.result.value {
                    let json = JSON(value)
                }
            case .Failure(let error):
                print(error)
            }
        }

2 个答案:

答案 0 :(得分:0)

试试这个:

Alamofire.request(.GET, url, parameters: parameters, headers: ["Accept": "application/json"]).responseJSON() { response in
        switch response.result {
        case .Success:
            if let value = response.result.value {
                let json = JSON(value)
            }
        case .Failure(let error):
            print(error)
        }
    }

答案 1 :(得分:0)

您必须使用自定义标头传递Alamofire NSMutableURLRequest。请查看此issue以获得更好的解释。

        var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL HERE")!)
        request.HTTPMethod = "GET"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept")
        //Add paramaters (Optional)
        let param = ["foo": "bar"]
        let encoding = Alamofire.ParameterEncoding.URL
        (request, _) = encoding.encode(request, parameters: param)
        Alamofire.request(request).responseJSON { response in
            //DO SOMETHING WITH YOUR RESPONSE OBJECT
        }

希望这会有所帮助:)