0

How to handle multipart in swift if you are dealing with multiple images having different keys and also having parameter dictionary with different kinds of key:value pairs like "String":"Any", "String":"[Any]", [[String:Any]].

let headers: HTTPHeaders = ["Content-type": "multipart/form-data"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        //Todo: - Images
        var c = 0
        for dictImage in arrImage {

            let validDict = kSharedInstance.getDictionary(dictImage)

            for keyName in validDict.keys {
                print(keyName)

                //Incr
                c += 1

                if let imageData = validDict[keyName] as? Data {

                    multipartFormData.append(imageData, withName: "\(keyName)", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")

                }

            }
        }


    }, usingThreshold: UInt64(), to: urlString, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded")

                if((response.result.value) != nil) {
                    debugPrint(response.result.value!)

                    let jsonData = JSON(response.result.value!)
                    if jsonData["status"].bool == true {
                        completion(jsonData.dictionaryObject!, true)
                    }else
                    {
                        completion(jsonData.dictionaryObject!, false)
                    }
                }
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            failure(error, false)
        }
    }

1 Answers1

0

Please check below code. Hope it helps you

  Alamofire.upload(
        multipartFormData: { MultipartFormData in
        for (key, value) in parameters {
            MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }

        for i in 0 ..< files.count {
            let fileName : String  = "image\(i).jpg"
            let datum : Data = files[i]
            MultipartFormData.append(datum, withName: fileParamName, fileName: fileName, mimeType: "image/jpg")
        }

    }, to: URLString, method: .post, headers: headers) { (result) in
        switch(result) {

        case .success(let upload, _, _):
            upload.responseJSON { response in

            }
            break;
        case .failure(_):
        }
    }