1

Can you help me out for upload image MultipartFormData with parameter and request authentication.

let username = "username"
let password = "password"

for request authentication

    let kurl = "Server url"
    let headers: HTTPHeaders = ["Authorization":"Basic \(base64EncodedCredential)"]
    let parmeter = ["name":"taykun","is_user":"1"]

        Alamofire.upload(multipartFormData: { (multipartFormData) in

                    }, to: kurl, encodingCompletion: { (result) in

                    })
Hitesh
  • 896
  • 1
  • 9
  • 22

1 Answers1

0

Try this code for alamofire:

   func uploadImageWithData(strApiUrl:String,strImageUrl:String,param:Dictionary<String, String>? = nil ,completionHandler: @escaping (_ result: NSDictionary) -> Void) -> Void{
            Alamofire.upload(multipartFormData: { multipartFormData in
                let urlImage:URL = URL.init(fileURLWithPath: strImageUrl)
                multipartFormData.append(urlImage, withName: "your key for image use in API")
                for (key, value) in param! {
                    multipartFormData.append(value.data(using:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
                }
            }, to: strApiUrl, encodingCompletion: {
                (encodingResult) in
                print("encoding result:\(encodingResult)")
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.uploadProgress(closure: { (Progress) in
                        print("Upload Progress: \(Progress.fractionCompleted)")
                        //send progress using delegate
                    })
                    upload.responseJSON{ (response) in                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
            })

        }


    func returnResponse (response: DataResponse<Any>)->NSDictionary
        {
            if (response.result.isSuccess)
            {
                if let value = response.result.value
                {
                    return value as! NSDictionary
                }
            }
            else
            {
                print("\(response.error?.localizedDescription)")
                var statusCode = 0
                if let error = response.result.error as? AFError {
                    statusCode = error._code // statusCode private
                    switch error {
                    case .invalidURL(let url):
                        print("Invalid URL: \(url) - \(error.localizedDescription)")
                    case .parameterEncodingFailed(let reason):
                        print("Parameter encoding failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                    case .multipartEncodingFailed(let reason):
                        print("Multipart encoding failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                    case .responseValidationFailed(let reason):
                        print("Response validation failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")

                        switch reason {
                        case .dataFileNil, .dataFileReadFailed:
                            print("Downloaded file could not be read")
                        case .missingContentType(let acceptableContentTypes):
                            print("Content Type Missing: \(acceptableContentTypes)")
                        case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                            print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
                        case .unacceptableStatusCode(let code):
                            print("Response status code was unacceptable: \(code)")
                            statusCode = code
                        }
                    case .responseSerializationFailed(let reason):
                        print("Response serialization failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                        // statusCode = 3840 ???? maybe..
                    }

                    print("Underlying error: \(error.underlyingError)")
                } else if let error = response.result.error as? URLError {
                    print("URLError occurred: \(error)")
                }else if let error = response.result.error as? NSError{
                  print("timeout")
                   statusCode = error._code
                }else {
                    print("Unknown error: \(response.result.error)")
                }

                print(statusCode)
                //make a response with nil value and set error or other information in it and return it.
                let paramDic:NSMutableDictionary = NSMutableDictionary()
                paramDic[KEY_MESSAGE] = response.error?.localizedDescription
                paramDic[KEY_DATA] = nil
                paramDic[KEY_STATUS_CODE] = "\(statusCode)"
                paramDic[KEY_SUCCESS] = 0

                return paramDic as NSDictionary
            }
            return NSDictionary()
        }

calling this method this way:

 let imgUrl = //first store  your image locally and then set image url
var dicParam = Dictionary<String , String>()//your requestparameter dictionary
        API.uploadImageWithData(strApiUrl: webserviceurl, strImageUrl: imgUrl, param: dicParam, completionHandler: { (result) in
          print(result)
          if result[KEY_SUCCESS] as! Int == 1{
           //success
          }else{
            //fail
          }
        })
Brijesh Shiroya
  • 3,323
  • 1
  • 13
  • 20
  • request url need basic authentication like let username = "username" let password = "password" How can i pass this? – Hitesh Jun 01 '17 at 07:34
  • simple make parameter dictionary and pass to func like,var dicParam = Dictionary() dicParam["uuername"] = "name" dicParam["password"] = "password" – Brijesh Shiroya Jun 01 '17 at 07:36
  • HTTPHeaders = authentication is required – Hitesh Jun 01 '17 at 09:42
  • you use post method or get? – Brijesh Shiroya Jun 01 '17 at 09:44
  • Alamofire.request(strUrl, method: HTTPMethod, parameters: param, encoding: URLEncoding.default, headers: nil).validate().responseJSON { (response) in completionHandler(self.returnResponse(response: response)) } – Brijesh Shiroya Jun 01 '17 at 09:48
  • using post method to upload image. – Hitesh Jun 01 '17 at 09:49
  • hi @BrijeshShiroyahi , could you please help my problem in uploading using alamofire ? tahnks in advance , maybe you have the answer. https://stackoverflow.com/questions/50327062/how-to-upload-an-image-using-alamofire-multipart-form-data-with-basic-authentica – sarah May 14 '18 at 09:31