Alamofire响应不匹配请求

时间:2016-01-21 05:12:01

标签: ios swift http-post alamofire http-get

我在通过Alamofire向我的API发出POST请求时遇到问题,GET没有问题,但是当我检查响应时,每当我发布POST时,我都会得到最后一次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)
})

我的代码首先获取状态列表,然后发布更新的用户配置文件。我的问题在于,当我收到更新的用户配置文件的响应时,它包含已经完成的早期GET请求的响应。 POST通过并在Web服务中进行更改,但我的响应对象中没有任何指示。

我已经确认服务器在发出POST请求时没有返回状态列表,当从浏览器手动调用时它会返回以下内容:

{
  "success": "Changes saved!"
}

我不知道为什么我从POST的早先请求中得到回复。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我想出来了。原来我必须在请求标题中添加“X-Requested-With”:“XMLHttpRequest”:

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

现在我正在从服务器正确获取响应。