AFnetworking: код ошибки 500: данные не могут быть прочитаны, потому что они не в правильном формате - PullRequest
0 голосов
/ 29 мая 2018

В моем приложении я использую AFNetworking для вызова API, и он отлично работает.Но для одного API, когда я вызываю этот API, он переходит в блок Failure и выдает ошибку, код ошибки 500: данные не могут быть прочитаны, поскольку они имеют неправильный формат.

ПРИМЕЧАНИЕ: этотолько дает ошибку, когда я добавляю массив в мой JSON.и когда я передаю эти данные в Почтальон, это дает мне правильный ответ.

Вот мой код:

func callAPIUsingPOSTAddActivity(filePath: String, params: NSMutableDictionary?, enableInteraction: Bool, showLoader: Bool, viewObj: UIView?, onSuccess: @escaping (AFAPICallerSuccess), onFailure: @escaping (AFAPICallerFailure)) {
    let strPath = Global.baseURLPath + filePath;


    print("URL = \(strPath) \n Param: \(String(describing: params))")
    var viewSpinner: UIView!
    if showLoader{
        viewSpinner = self.addShowLoaderInView(viewObj: viewObj!, boolShow: showLoader, enableInteraction: enableInteraction)!
    }
    let afManager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
    let authValue = Global.kLoggedInUserData().AccessToken
    if authValue != nil || authValue != ""
    {
        afManager.requestSerializer.setValue(authValue, forHTTPHeaderField: "Authorization")

    }

             let headerSet = NSSet(objects: "application/json")
    afManager.responseSerializer.acceptableContentTypes = headerSet as! Set<String>


    var jsonString : String = ""
    if (params != nil)
    {
        let jsonData = try? JSONSerialization.data(withJSONObject: params, options: [])
        jsonString = String(data: jsonData!, encoding: .utf8)!
    }
    else
    {
        jsonString = ""
    }


    afManager.post(strPath, parameters: jsonString, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in

        if showLoader{
            self.hideRemoveLoaderFromView(removableView: viewSpinner, mainView: viewObj!)
        }


        let dictResponse = responseObject as! NSDictionary
        //   print(dictResponse)
        if (dictResponse.object(forKey: "flag") as! Bool == true) || (dictResponse.object(forKey: "flag") as? Int == 1) { //no error
            onSuccess(dictResponse, true)

        }
        else { //with error
            if (showLoader) {
                if ((dictResponse.object(forKey: "flag") as? String) != nil){
                    print(dictResponse)
                    Global.singleton.showWarningAlert(withMsg: dictResponse.object(forKey: "response") as! String)
                }
            }
            onSuccess(dictResponse, false)
        }
    }) { (task: URLSessionDataTask?, error: Error) in
        onFailure()
        if let response = task?.response as? HTTPURLResponse {
            print(response.statusCode)
            if response.statusCode == 401 {
                AFAPICaller().callAPIUsingTOKEN_Refresh_POST(enableInteraction: true, showLoader: false, viewObj: nil, onSuccess: { (_, _) in

                }, onFailure: {

                })
            }
        }
        if (showLoader) {
            print(error.localizedDescription)
            Global.singleton.showWarningAlert(withMsg: LocalizeHelper().localizedString(forKey: "keyInternetMsg"))
            self.hideRemoveLoaderFromView(removableView: viewSpinner, mainView: viewObj!)
        }

    }
}

, а вот строка json, которую я передаю

{"is_all_day":false,"account_type":"3","activity_type_id":"1","conference_call_pin":"","event_description":"","people_involved":[{"last_name":"","org_logo_url":{"big":"","small":"app\/assets\/images\/no_user.png"},"id":"12","country":"","question_id":"","ignore_contact":false,"contact_pic":"","option_id":"","address_line_2":"","contact_pic_url":{"big":"","small":"app\/assets\/images\/no_user.png"},"state":"","organization_logo":"","work_country":"","work_address_line_2":"","key":"new","address_line_1":"","fname":"kashish","work_city":"","email":"","is_support_user":false,"work_state":"","link_to_organization":false,"is_associate":false,"work_full_address":"","org_id":"","zip_code":"","is_custom":false,"city":"","work_zip_code":"","first_name":"kashish ","org_email":"","contact_id":"12","work_is_custom":"","select_to_invite":false,"full_address":"","company_name":"Tata Consultancy Services","organization_name":"","work_address_line_1":""}],"duration":"01:00","location_type":"","end_date":"05\/29\/2018","is_custom":false,"organization_involved":[],"assign_to":"1","is_duration":true,"calendar_master_id":"","is_repeat":false,"event_title":"Call","purpose_type_trans_id":"","conference_description":"","conference_call_type_id":"","purpose_description":"","event_location":"","start_date":"05\/29\/2018","start_time":"11:00","conference_custom_type":"","is_address":false}

когда я передаю это почтальону, он работает нормально.Я пытаюсь из последних двух дней.помогите, если у вас есть решение.

enter image description here

...