Search code examples
iosswiftswift3alamofireimage-uploading

Upload Multipart swift Image Upload internal server error 500 in response


I migrated to swift 3 for which i have to Upgrade Alamofire to 4, Upload image with mulitpart request is working fine in swift 2 and same API with same params getting internal server error 500 in success here are is swift 2.3 code which is working fine

        Alamofire.upload(
        .POST,
        AppConstants.kAPIBaseURL  + AppConstants.KAPIWidgetUrl + AppConstants.KAPIUpdateUserPhoto,headers: headers,
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(data: imageData!, name: "image[image]", fileName: "myImage.png", mimeType: "image/png")
            multipartFormData.appendBodyPart(data: "\((UserManager._currentUser?.userID)!)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"id")
            multipartFormData.appendBodyPart(data: "profile_picture".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"upload_to")


        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):

                upload.responseJSON { (JSON) in
                    let abc   = JSON.result.value as! NSDictionary
                    print(abc)
                    let arrayOfResult = abc["results"] as! NSDictionary
                    let responseMessage = abc["message"] as! String
                    let currentUser: MOUser?
                    currentUser = MOUser.init(object: arrayOfResult)
                    UserManager.setCurrentUser(currentUser)
                    dispatch_async(dispatch_get_main_queue(),{
                        //Show Alert in UI
                        print("image uploaded");
                        [self.showAlertViewWithTitle(AppConstants.kEmptyString, message: "\(responseMessage)", dismissCompletion: {

                        })]
                    })
                }

            case .Failure(let encodingError):
                print(encodingError);
            }
        }
    );

and below is the Swift 3 code with error

Alamofire.upload(
        multipartFormData: { multipartFormData in

            multipartFormData.append(imageData!, withName: "image[image]", fileName: "myImage.png", mimeType: "image/png")
            multipartFormData.append("\(UserManager._currentUser?.userID)".data(using: .utf8, allowLossyConversion: false)!, withName: "id")
            multipartFormData.append("profile_picture".data(using: .utf8, allowLossyConversion: false)!, withName: "upload_to")


    },
        to: AppConstants.kAPIBaseURL  + AppConstants.KAPIWidgetUrl + AppConstants.KAPIUpdateUserPhoto ,method: .post, headers: headers,
        encodingCompletion: { encodingResult in
            print(encodingResult)
            switch encodingResult {

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

                    print("SUCCESS RESPONSE: \(response)")
                    SVProgressHUD.dismiss()
                    if let info = response as? Dictionary<String, AnyObject> {

                        if let links = info["links"] as! Dictionary<String, AnyObject>? {
                            if let imgLink = links["image_link"] as? String {

                                print("LINK: \(imgLink)")

                            }
                        }

                    }

                }

                upload.uploadProgress { progress in

                    print(progress.fractionCompleted)
                }

                upload.responseString(completionHandler: { (response) in
                    print(response)
                    print(response.data)
                    print(response.debugDescription)
                    print(response.description)
                    print(response.result.description)
                    print(response.response)
                })



            case .failure(let encodingError):
                SVProgressHUD.dismiss()
                print("ERROR RESPONSE: \(encodingError)")

            }//switch

    }
    );

Server Error is this

SUCCESS: {"status":"500","error":"Internal Server Error"}
SUCCESS
Optional(<NSHTTPURLResponse: 0x60000123cda0> { URL: https://../api///imageupload } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 48;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 11 Jan 2017 13:45:59 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.0.0/2015-12-16)";
Via = "1.1 vegur";
"X-Rack-Cache" = "invalidate, pass";
"X-Request-Id" = "78cc7e5c-9bc1-4802-beac-15f8f7c4400a";
"X-Runtime" = "0.167883";

If Anybody can help me on this. Thanks!


Solution

  • There is a difference in this line:

    multipartFormData.append("\(UserManager._currentUser?.userID)".data(using: .utf8, allowLossyConversion: false)!, withName: "id")`. 
    

    You don't force unwrap the UserManager._currentUser?.userID like you do in the 2.3 version:

    multipartFormData.appendBodyPart(data: "\((UserManager._currentUser?.userID)!)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"id")
    

    So your string for that "id" field is probably something like "Optional("userID")" instead of just the user ID you're expecting.