简体   繁体   中英

Alamofire response not matching request

I am having an issue when making a POST request to my API via Alamofire, GETs work without issue, however whenever I make a POST when I check the response I get the results of the last GET.

import Alamofire
import SwiftyJSON

class NetworkManager {
    static let sharedInstace = NetworkManager()

    let defaultManager: Alamofire.Manager = {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "homestead.app": .DisableEvaluation
        ]

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders

        return Alamofire.Manager(
            configuration: configuration,
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )
    }()
}

internal class ApiHelper {

    /**
     Get data from a target URL and return JSON data to be parsed

     - parameter targetURL: URL to pull data from
     - parameter success:   return data to the calling function
     - parameter failure:   return an error message to the calling function
     */
    private func getDataFromAPI(targetURL: String, success:(JSONData: JSON) -> (), failure:(message: String) -> ())  {

        NetworkManager.sharedInstace.defaultManager.request(.GET, targetURL).responseJSON { response in
            print(response.result)
            switch response.result {
            case .Success:
                if let jsonRaw = response.result.value {
                    let json = JSON(jsonRaw)

                    success(JSONData: json)

                }
            case .Failure(let error):
                print(error.localizedDescription)
                failure(message: error.localizedDescription)
            }
        }
    }

    /**
     Post data to the target URL and return errors as JSON data to be parsed

     - parameter targetURL:  URL to post to
     - parameter parameters: JSON data to post
     - parameter success:    return success message to the calling function
     - parameter failure:    return JSON data to the calling function with server error
     */
    private func postDataToAPI(targetURL: String, parameters: [String : AnyObject], success:() -> (), failure:(JSONData: JSON) -> ())  {

        NetworkManager.sharedInstace.defaultManager.request(.POST, targetURL, parameters: parameters, encoding: .JSON).responseJSON { response in
            debugPrint(response)

            success()
        }
    }


    /**
     Post an updated profile to the API

     - parameter parameters: JSON data to be posted
     - parameter success:    success callback
     - parameter failure:    JSON data of serverError
     */
    internal func postUpdateRequest(parameters: [String : AnyObject], success:() -> (), failure:(JSONData: JSON) -> ()) {
        let url = "https://homestead.app/profile/a/update"

        postDataToAPI(url, parameters: parameters, success: {
            success()
            }, failure: { JSONData in
                failure(JSONData: JSONData)
        })
    }

    /**
     Get all states from the API

     - parameter success: JSON data of all states
     - parameter failure: failure message
     */
    internal func getAllStates(success:(JSONData: JSON) -> (), failure:(message: String) -> ()) {
        let url = "https://homestead.app/api/state/all"
        getDataFromAPI(url, success:
            { JSONData in
                success(JSONData: JSONData)
            }, failure: { message in
                failure(message: message)
        })
    }
}

let api = ApiHelper()
api.getAllStates({ JSONdata in
    print(JSONdata)
    let params: [String : AnyObject] = ["name" : "Bob"]
    api.postUpdateRequest(params, success: { JSONdata in
        print("Success")
        }, failure: { message in
            print("Message")
    })
    }, failure: { message in
        print(message)
})

My code first gets the list of states and then posts an updated user profile. My issue is in that when I get the response for that updated user profile, it includes the response from the earlier GET request that had already been completed. The POST goes through and the changes are made in the web services, but I have no indications in my response object.

I have confirmed the server does not return the list of states when making a POST request, it returns below when called manually from the browser:

{
  "success": "Changes saved!"
}

I'm at a loss on why I am getting a response from an earlier request from my POST. Any thoughts?

I figured this out. It turned out I had to add "X-Requested-With": "XMLHttpRequest" to the requests header:

   configuration.HTTPAdditionalHeaders = [
            "X-Requested-With": "XMLHttpRequest"
        ]

Now I am getting the responses correctly from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM