ios - Alamofire 响应返回 nil 但在 Postman 上工作

标签 ios swift alamofire

我有参数:

{"name": "oaseme dabo", "spouseName": "", "fatherName": "hajime kasuga", "income": "Please Choose", "homeAddress": "", "locationAccessibility": "Please Choose", "gender": "Please Choose", "exactOccupation": "", "maritalStatus": "Please Choose", "source_id": "123456", "dateOfBirth": "01 January 1900", "exactIncome": "1", "howInfluenceThisPerson": "Please Choose", "motherName": "shizuka kasuga", "knowThisPerson": "Please Choose", "prospectingStatus": "Please Choose", "ageBand": "Choose Age Band", "occupation": "Please Choose", "sourceOfProspect": "Family & Relatives", "agentCode": "123456", "totalChildren": "0", "howCloseAreYou": "Please Choose", "workAddress": "", "exactSourceOfProspect": ""}

我把它放进 body 里:

class func sentContactBody(agentCode: String, source_id: String, dateOfBirth: String, ageBand: String, exactIncome: String, exactOccupation: String, fatherName: String, gender: String, homeAddress: String, howCloseAreYou: String, howInfluenceThisPerson: String, income: String, knowThisPerson: String, locationAccessibility: String, maritalStatus: String, motherName: String, name: String, occupation: String, prospectingStatus: String, sourceOfProspect: String, spouseName: String, totalChildren: String, workAddress: String, exactSourceOfProspect: String) -> Parameters{
    let sentContact : Parameters = [
        "agentCode": agentCode,
        "source_id": source_id,
        "dateOfBirth": dateOfBirth,
        "ageBand": ageBand,
        "exactIncome": exactIncome,
        "exactOccupation": exactOccupation,
        "fatherName": fatherName,
        "gender": gender,
        "homeAddress": homeAddress,
        "howCloseAreYou": howCloseAreYou,
        "howInfluenceThisPerson": howInfluenceThisPerson,
        "income": income,
        "knowThisPerson": knowThisPerson,
        "locationAccessibility": locationAccessibility,
        "maritalStatus": maritalStatus,
        "motherName": motherName,
        "name": name,
        "occupation": occupation,
        "prospectingStatus": prospectingStatus,
        "sourceOfProspect": sourceOfProspect,
        "spouseName": spouseName,
        "totalChildren": totalChildren,
        "workAddress": workAddress,
        "exactSourceOfProspect": exactSourceOfProspect
    ]

    return sentContact
}

我称它为参数:

let param = HTTPBody.sentContactBody(agentCode: agentCode, source_id: source_id, dateOfBirth: dateOfBirth, ageBand: ageBand, exactIncome: exactIncome, exactOccupation: exactOccupation, fatherName: fatherName, gender: gender, homeAddress: homeAddress, howCloseAreYou: howCloseAreYou, howInfluenceThisPerson: howInfluenceThisPerson, income: income, knowThisPerson: knowThisPerson, locationAccessibility: locationAccessibility, maritalStatus: maritalStatus, motherName: motherName, name: name, occupation: occupation, prospectingStatus: prospectingStatus, sourceOfProspect: sourceOfProspect, spouseName: spouseName, totalChildren: totalChildren, workAddress: workAddress, exactSourceOfProspect: exactSourceOfProspect)

当我使用Alamofire调用时,它总是返回nil所以算作失败:

Alamofire.request(Constant.sentContactSAMDB(), method: .post, parameters: param, encoding: JSONEncoding.default, headers: ConnectionManager.sharedIns.getHTTPHeadersSAMDB())
        .responseObject{ (response: DataResponse<SAMDBModel>) in
            switch(response.result) {
            case .success(_):
                print("contact response result value:\(response.result.value)")
                if response.result.value != nil {
                    self.samDBModel = response.result.value
                    let status = self.samDBModel?.status
                    let statusCode = response.response?.statusCode
                    print("sent contact statusCode:\(String(describing: statusCode))")
                    if(statusCode == 200){
                        let result = self.samDBModel?.result
                        let samDBStatus = result![0].status
                        let samDBError = result![0].error
                        print("sent contact samDBStatus:\(samDBStatus)")
                    }
                }
                break

            case .failure(_):
                print("contact failure response result value:\(response.result.value)")
                self.samDBModel = response.result.value
                let status = self.samDBModel?.status ?? "Failed connect to Tokio Marine server"
                break

            }
    }

但它适用于 Postman: enter image description here

header 只有 Content-Type : application/json

让它工作的正确代码是什么?我已经放置了 plist 异常域并允许任意加载是。

最佳答案

像这样正确设置请求正文和 header :

let data = try! JSONSerialization.data(withJSONObject: your_parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
var request = URLRequest(url: your_URL)
request.httpBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

关于ios - Alamofire 响应返回 nil 但在 Postman 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015771/

相关文章:

ios - Swift:Apple Mach-O 链接器 (id) 错误 - Xcode 8.3

ios - 如何使用 Alamofire 发送 SwftyJSON?

xml - 如何在 Swift 2.0 中使用 Alamofire 3.0 .responsePropertyList?

Swift 3/Alamofire 4 迁移,必须为 [String : AnyObject] 制作所有元素 'as AnyObject'

ios - 为什么 SKProductsRequestDelegate/SKRequestDelegate didFailWithError 在 NSError 上抛出 EXC_BAD_ACCESS?

ios - 恢复应用程序崩溃时的 Phonegap

iOS App运行后台任务时间

ios - Swift Admob 控制台显示模拟器设备 ID 但在 iPhone 上运行时不显示?

ios - assetExport完成后检索路径

ios - 陷入循环。很奇怪,因为代码有时可以工作,有时只是卡住