Swift Alamofire 4 add header to request without custom request adapter

a 夏天 提交于 2020-01-07 03:10:26

问题


I am trying to migrate to the new alamofire, and in the docs it tells me i need to do a custom request adapter in order to add headers to requests, i think thats not confortable everywhere and i would like to just add the header in the request instead of having to make an adaper for certain requests, anyone have found a way to do it?

below i shared my old code (commented) and my new code wich is missing a header parameter.

            Alamofire.request(url, method: .post , parameters: parameters, encoding: JSONEncoding.default)
                .responseJSON { response in
                    if response.result.isSuccess {
                        let time = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds) + Double(1 * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
                        DispatchQueue.main.asyncAfter(deadline: time) {
                            self.loadAreasFromServer();
                            self.busy = false;
                        }
                    }
            }

            /*Alamofire.request(.POST, url,headers:headers,parameters:parameters,
                encoding: .json)
                .responseJSON { response in
                    if response.result.isSuccess {
                        let time = DispatchTime(DispatchTime.now()) + Double(1 * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
                        DispatchQueue.main.asyncAfter(deadline: time) {
                            self.loadAreasFromServer();
                            self.busy = false;
                        }
                    }
            }*/

回答1:


The method signature changed. This should work for you:

Alamofire.request(url, method: .post , parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    .responseJSON { response in
        if response.result.isSuccess {
            let time = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds) + Double(1 * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
            DispatchQueue.main.asyncAfter(deadline: time) {
                self.loadAreasFromServer();
                self.busy = false;
            }
        }
}


来源:https://stackoverflow.com/questions/40247922/swift-alamofire-4-add-header-to-request-without-custom-request-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!