Home > Blockchain >  How to send array parameter in alamofire multipartform?
How to send array parameter in alamofire multipartform?

Time:12-28

I have an array, several parameters

var arr: [String] = [ "a", "b", "c", "d", "e"]
...

let parameters: [String: Any] = [
    "myArray" : self.arr,
    "text"    : self.text
    ...
]

I want to upload

AF.upload(mutlipartFormData: { multipart in 
    for (key, value) in parameters {
        if key == "myArray" {
            // This code is problem
            for idx in value as! [String] {
            multipartFormData.append("\(idx)".data(using: .utf8, allowLossyConversion: false)!, withName: "\(key)")
                    }
        }
    }

I tried that code, It uploaded just 1 element in arr. I want to send the array

CodePudding user response:

you just need to convert your array in JSON String.

var arr: [String] = [ "a", "b", "c", "d", "e"]
var strArr = ""
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: arr,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    strArr = theJSONText ?? ""
    print("JSON string = \(theJSONText!)")
}


let param: [String: Any] = [
    "myArray" : strArr,
    "text"    : "text"
]
print(param)

        
Alamofire.upload(multipartFormData: {
    multipartFormData in
    for (key, value) in param {
        multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
    }
}, to: "apiurl", method: .post, encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.responseJSON {
            response in
            print(response.result)
        
        }

    case .failure(let encodingError):
            break
    }
})        

CodePudding user response:

-->you can create a function for uploading form data like this

func makeFormDataAPICallDecodable<T: Codable>(url: String, params: [String: Any], objectType: T.Type,
                                                  success: @escaping(_ responseObject: T) -> Void,
                                                  failure: @escaping (_ error: String) -> Void) {
            // Almofire upload request
            AF.upload(multipartFormData: { multiPartData in
                for (key, value) in params {
                    if value is UIImage {
                        let img = (value as? UIImage)?.jpegData(compressionQuality: 0.5)
                        multiPartData.append(img!, withName: key, fileName: "img_\(name).jpeg", mimeType: "image/jpeg")
                    } else if value is NSArray {
                        for childValue in value as? NSArray ?? [] {
                            if childValue is UIImage {
                                let img = (childValue as? UIImage)?.jpegData(compressionQuality: 0.5)
                                multiPartData.append(img!, withName: key, fileName: "profile_image.png", mimeType: "image/jpeg")
                            }
                        }
                    } else if value is NSURL || value is URL {
                        do {
                            guard let pdf: URL = value as? URL else { return }
                            let name = pdf.lastPathComponent
                            let mimeType = pdf.mimeType()
                            let pdfData = try Data(contentsOf: pdf)
                            multiPartData.append(pdfData, withName: key, fileName: name, mimeType: mimeType)
                        } catch { print(error) }
                    } else {
                        if value is String || value is Int || value is Bool {
                            multiPartData.append("\(value)".data(using: .utf8)!, withName: key)
                        }
                    }
                }
            }, to: urlIs,method: .post, headers: headers).responseDecodable(of: FetchAPI<T>.self) { response in
                // preetify data
                if let data = response.data {
                    let str = data.prettyPrintedJSONString!
                    Logger.logResponse(ofAPI: "\(urlIs)", logType: .success, object: str)
                }
                // response result
                switch response.result {
                case .success(let data):
                    // check auth token Exp condition
                    if data.statusCode == 401 {
                        self.navigateToLogin()
                        return
                    }
                    // check flag status
                    if data.flag! { success(data.data!) } else { failure(data.message!) }
                case .failure(let error):
                    failure("Something went wrong.")
                    Logger.log(logType: .error, object: error.localizedDescription)
                }
            }
        } else { failure(ServerAPI.errorMessages.kNoInternetConnectionMessage) }
    }

-> You can use it like

let params: [String : Any] = [User.CodingKeys.userName.rawValue: data.name!,
                                      User.CodingKeys.email.rawValue: data.email!,
                                      User.CodingKeys.userRole.rawValue: data.userRole!,
                                      User.CodingKeys.phoneNumber.rawValue: data.phoneNumber!,
                                      kPassword: data.password!,
                                      User.CodingKeys.employeeID.rawValue: data.employeeId!,
                                      User.CodingKeys.departmentID.rawValue: data.department!,
                                      kDeviceType:1] // ["Key": value]

makeAPICallDecodable(url: ServerAPI.register, params: params, objectType: User.self, success: {
            response in
            print(response)
        }, failure: { error in
            print(error)
        })

-> parameter objectData is the object in which you want response is an generic <T.type>

  • Related