Search code examples
iosswiftimage-uploadingmultipartform-dataafnetworking-2

Multiple Image upload using AFNetworking Multipart form data not working


I am trying to upload multiple images as multipart for data using AFNetworking 2.6.3 in my Swift project

Here is my code of appending data to form data

self.webserviceHandler.post(serviceName, parameters: nil, constructingBodyWith: { (data:AFMultipartFormData) in
                for i in 0..<imageArray.count{
                    let imagData = UIImageJPEGRepresentation(imageArray[i], 0.5)
                    data.appendPart(withFileData: imagData!, name: "MenaImage[]", fileName: fileNameArray[i], mimeType: "image/jpeg")

                }

                for (key, value) in parameters{
                    data.appendPart(withForm: "\(value)".data(using: .utf8)!, name: key as! String)
                }
            }, success: { (operation:AFHTTPRequestOperation!, responseObject:Any!) in
                successResponseClosure(responseObject as AnyObject)
            }) { (operation:AFHTTPRequestOperation!, error:Error!) in
                    errorClosure(error as NSError)
                }

webserviceHandler is AFHTTPRequestOperationManager shared class.

initialization of AFHTTPRequestOperationManager

init() {
        let baseURL = URL(string:"http://test.com/")!
        self.webserviceHandler = AFHTTPRequestOperationManager(baseURL:baseURL)
        self.webserviceHandler.requestSerializer = AFJSONRequestSerializer()
        self.webserviceHandler.responseSerializer = AFJSONResponseSerializer()

        let contentType = NSString(string:"text/html")
        let contentTypes = NSMutableSet(set:self.webserviceHandler.responseSerializer.acceptableContentTypes!)
        if contentTypes.contains(contentType) == false{
            contentTypes.add(contentType)
            self.webserviceHandler.responseSerializer.acceptableContentTypes = contentTypes as Set<NSObject>

        }

Here is the request logged by AFNetworkActivityLogger

{
    "Accept-Language" = "en-BH;q=1, ar-BH;q=0.9, en-GB;q=0.8";
    "Content-Length" = 3023913;
    "Content-Type" = "multipart/form-data; boundary=Boundary+F955A845D801084F";
    "User-Agent" = "MBB/1.0 (iPhone; iOS 11.2.5; Scale/2.00)";
} (null)

Please help to fix this.


Solution

  • Finally resolved the issue. It was a problem at server side. There was code snippet to log the request receiving from apps. When the image there is large size image in request, this code throws error. When that code is removed its working perfectly. Hope this helps others also.