iosswiftalamofire

Swift Alamofire 4 add header to request without custom request adapter


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 that's not comfortable everywhere and I would like to just add the header in the request instead of having to make an adapter for certain requests, anyone have found a way to do it?

below I shared my old code (commented) and my new code which 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;
                        }
                    }
            }*/

Solution

  • 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;
                }
            }
    }