Загрузка изображения Alamofire с пользовательским запросом, получая 400 кодов статуса в ответ - PullRequest
0 голосов
/ 20 апреля 2020

Получение 400 кода состояния в ответ. Мне нужно передать строку JSON с файлом, состоящим из нескольких частей, используя alamo fire, или любой другой способ для этого. Я проверил почтальона, и он отлично работает над их справкой.

Если есть другой способ загрузить многокомпонентный файл со строкой JSON в swift, то также предложите

class func POSTMultipartRequestWithJsonParm<T: BaseMappable>(url : apiCall,  userID:String?, parameterDitionary: [String : Any]? , parameterwithImage : [String : Data]?, responseModel: Mapper<T>,  success:(( AnyObject ) -> Void)?) {

           if Utility.currentReachabilityStatus == .notReachable {
               let toast = Toast(text:"Please check your internet connection and try again.")
               toast.show()
               return
           }

          // appDelegate.showLoader()

           var finalDisParameter :[String : Any]
           finalDisParameter = parameterDitionary!

           if let api_token = utility.getUserDefault(kApiToken), url != apiCall.createAccount {
               finalDisParameter["api_token"] =  api_token as? String
           }

           var user_ID :String!
           if let myuserId = userID {
               user_ID =  myuserId
           }else{
               user_ID = ""
           }

        print(mainUrl + url.rawValue + "\(user_ID!)")
        print(HeaderClass.objHeaderClass.HeaderDictionary)

        var request = URLRequest(url: URL(string: mainUrl + url.rawValue)!)
            request.httpMethod = "POST"
            request.httpBody = try? JSONSerialization.data(withJSONObject: finalDisParameter, options: [])
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.allHTTPHeaderFields = HeaderClass.objHeaderClass.HeaderDictionary

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            for (key, value) in parameterwithImage! {
                multipartFormData.append(value, withName: "\(key)", fileName: "\(key)" + ".png", mimeType: "image/png")
            }

            }, with: request) { (result) in
                       switch result {
                       case .success(let upload, _, _):

                           upload.uploadProgress(closure: { (Progress) in
                               print("Upload Progress: \(Progress.fractionCompleted)")
                           })

                           upload.responseJSON { response in
                               //self.delegate?.showSuccessAlert()
                               print(response.request as Any)  // original URL request
                               print(response.response as Any) // URL response
                               print(response.data!)     // server data
                               print(response.result)   // result of response serialization

                               BaseReqeustClass.HandleResponse(apicallMethod: url,apiResponse: response , successHandler: { (BaseModel) -> Void in

                                   let shareobj = responseModel.map(JSON: (BaseModel.data))
                                   success!(shareobj as AnyObject)
                               })
                           }

                       case .failure(_):
                           appDelegate.hideLoader()
                           print(result)
                           break
                       }
                   }
       }

Функция Позвонить Запрос

    func getCreditCardDetail() {
        do {
            let dic1 = ["applicantDetails": ["applicantPreviousAddress": ["address": "string", "city": "string", "howLong": 0, "postalCode": "string", "province": "string"], "currentHousingSituation":  ["isOwnWithMortgage": false, "mortgagePayment": 0, "isOwnFreeAndClear": false, "isRent": false,         "isLiveWithFamily": false, "isOthers": false, "mortgageCompany": "string", "marketValue": 0, "balanceOwing": 0, "rent": 0, "otherString": "string"], "dateOfBirth": "string", "howLong": 0, "phoneNumber": "string", "socialInsuranceNumber": "string"], "bookingDateTime": "string", "carId": 1, "constantId": [ "constantIdForSlotTerm": 0, "mileagePackageId": 0, "wearCareId": 0], "deliveryLocationAdded": true, "distance": 0, "employmentDetails" : ["currentEmployment": ["address": "string","applicantEmployer": "string","city": "string","grossIncome": 0,
            "howLong": 0,"occupation": "string","postalCode": "string", "province": "string",
            "workPhoneNumber": "string"], "otherSourceGrossIncome": 0, "otherSourceHowLong": 0, "otherSourceIncome": "string", "previousEmployment": ["address": "string", "applicantEmployer": "string", "city": "string", "grossIncome": 0,
            "howLong": 0, "occupation": "string", "postalCode": "string", "province": "string", "workPhoneNumber": "string"]], "fromDate": "string", "isDeliveryLocationAdded": true, "isMileagePackageSelect": true,
            "isWearCareAdd": true,"mileagePackageSelect": true, "toDate": "string",
            "totalPayment": 0,"wearCareAdd": true] as [String: Any]

            let jsonData1 = try JSONSerialization.data(withJSONObject: dic1, options: .fragmentsAllowed)

            let theJSONText = String(data: jsonData1, encoding: .utf8)!
            let imageData = self.btnSignature.imageView?.image?.pngData()
            let imgParam  = ["userSignature": imageData!]
            let params = ["addUserCreditScoreReqDto":theJSONText] as Dictionary<String, Any>

            BaseReqeustClass.POSTMultipartRequestWithJsonParm(url: apiCall.creditCard, userID: nil, parameterDitionary: params, parameterwithImage: imgParam, responseModel: Mapper<MobileVerificationModel>()) { (_) in

            }
        } catch {
        }
    }

Здесь я также отправляю ответ

{ Status Code: 400, Headers {
    "Cache-Control" =     (
        "no-cache, no-store, max-age=0, must-revalidate"
    );
    Connection =     (
        close
    );
    "Content-Length" =     (
        0
    );
    Date =     (
        "Mon, 20 Apr 2020 10:57:28 GMT"
    );
    Expires =     (
        0
    );
    Pragma =     (
        "no-cache"
    );
    "Strict-Transport-Security" =     (
        "max-age=31536000 ; includeSubDomains"
    );
    "X-Content-Type-Options" =     (
        nosniff
    );
    "X-Frame-Options" =     (
        DENY
    );
    "X-XSS-Protection" =     (
        "1; mode=block"
    );
} })
...