Facing problem while uploading images with Alamofire multipart data - ios

I'm getting this message in console:
findWriterForTypeAndAlternateType:119: unsupported file format 'public.heic'
And getting empty JSON as response hence always showing Failed, Something went wrong
My code:
func alamofireMultipart2<T: Decodable>(urlString: String, body: [String: String], images: [(image: UIImage, param: String, fileName: String)], resultType: T.Type, completion: #escaping ([String: Any]?, String, String) -> Void) {
print("Inside Alamofire multipart")
guard let url = URL(string: urlString) else {
print("Invalid URL: " + urlString)
return
}
let header = ["Authorization" : "Bearer \(AppConfigs.accessToken)"]
Alamofire.upload(
multipartFormData: { multipartFormData in
print("body:")
body.forEach {
key, value in
print("key: \(key), value: \(value)")
multipartFormData.append(Data(value.utf8), withName: key)
return
}
images.forEach {
(image, param, filename) in
let imageData = image.jpegData(compressionQuality: 0.8)
print("Image Size = \(imageData?.count.byteSize)")
multipartFormData.append(imageData!, withName: param, fileName: filename, mimeType: "image/jpeg")
}
},
to: url,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print("\n\nupload result, response: ")
print(response)
print("Error: ")
print(response.error ?? "null")
guard let data = response.data else {
print("response.data is nil")
return
}
let serializedData = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let parsedData = serializedData else {
print("Could not parse json")
completion(nil, "Failed", "Something went wrong")
return
}
let status = parsedData["status"] as? String ?? "Failed"
let message = parsedData["message"] as? String ?? "Something went wrong"
if status == "OK" {
print("Response parsed successfully! status is OK")
completion(parsedData, status, message)
} else {
print("status is not OK")
completion(nil, status, message)
}
}
case .failure(let encodingError):
print("Status Code: ")
print("Error!")
print(encodingError)
}
})
}

Related

Not able to upload camera images using Almofire multipart

I have to upload images, audio, documents. I'm using Alamofire to upload. Everything is uploaded including gallery images like screenshots, but pictures taken from camera are not getting uploaded.
Here's my code:
func requestUploadFileWithMultipart(connectionUrl: String, param : [String: AnyObject], filePath: String?, _ callBack: #escaping (_ data: DataResponse<Any>?, _ error:Error?) -> Void) {
let URLString = MainURL + connectionUrl
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
let stringValue = "\(value)"
multipartFormData.append(stringValue.data(using: String.Encoding.utf8)!, withName: key)
print("Key: \(key), Value: \(stringValue)")
}
if filePath != "" {
do {
var fileData = try Data(contentsOf: URL(string: filePath!)!)
let ext = URL(fileURLWithPath: filePath!).lastPathComponent.components(separatedBy: ".").last
let mime = filePath?.mimeTypeForPath()
let fileName = "\(Date().timeIntervalSince1970)".components(separatedBy: ".").first
multipartFormData.append(fileData, withName: "file", fileName: "\(fileName ?? "file").\(ext ?? "")", mimeType: mime ?? "")
} catch {
print("error loading file in multipart")
}
}
}, to:URLString) { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value as Any)
callBack(response, nil)
}
case .failure(let encodingError):
print(encodingError)
callBack(nil, encodingError)
}
}
}
Image compression worked for me. May be large files were no uploading.
Please try below code, I am using this code in my one of project. But make sure that API is suitable for multipart uploading.
Alamofire.upload(multipartFormData: {
multipartFormData in
if let img = image {
if let imageData = img.jpegData(compressionQuality: 0.4) {
multipartFormData.append(imageData, withName: "cmt_img", fileName: "\(Date()).jpg", mimeType: "image/jpg")
}
}
do {
let theJSONData = try JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions(rawValue: 0))
multipartFormData.append(theJSONData, withName: "data")
} catch {}
},usingThreshold: 0 ,to: baseURL + URLS.AddComment.rawValue, headers: appDelegate.headers, encodingCompletion: {
encodingResult in switch encodingResult {
case .success(let upload, _, _):
upload.responseObject(completionHandler: { (response: DataResponse<AddCommentData>) in
SVProgressHUD.dismiss()
if (response.result.value != nil) {
showAlert(popUpMessage.uploadingSuccess.rawValue)
}
else {
showAlert(popUpMessage.someWrong.rawValue)
}
})
break
case .failure(let encodingError):
SVProgressHUD.dismiss()
print(encodingError)
break
}
})
}

upload image from multipart-from-data using Alamofire '~> 5.0.0-beta.3'

func uploadImage(image: UIImage, imageUrl: String, imageExtension: String , responseData: #escaping (_ response: UploaderModel)-> ()) {
var status : UploaderModel?
let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
let authorization = ["Authorization" : "Bearer \(token)"]
let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"
//Parameter HERE
let parameters = [
"garbageCollector": 0,
"stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
"delete_file" : ""
] as [String : Any]
//Header HERE
let headers: HTTPHeaders
headers = ["Content-type": "multipart/form-data",
"Content-Disposition" : "form-data"]
guard let imgData = firstImage.image?.jpegData(compressionQuality: 0.7) else { return }
AF.upload(multipartFormData: { multipartFormData in
//Parameter for Upload files
multipartFormData.append(imgData, withName: "file",fileName: imageUrl , mimeType: "image/\(imageExtension)")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, usingThreshold:UInt64.init(),
to: imageURl, //URL Here
method: .post,
headers: headers, //pass header dictionary here
interceptor: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Uploading")
})
upload.responseJSON { response in
print("the resopnse code is : \(response.response?.statusCode)")
print("the response is : \(response.description)")
let json = JSON(response.data)
if let msg = json["msg"].string {
status.msg = msg
}
if let stat = json["status"].int {
status.status = stat
}
responseData(status)
}
break
case .failure(let encodingError):
print("the error is : \(encodingError.localizedDescription)")
break
}
} )
}
error : Cannot convert value of type '(_) -> ()' to expected argument type 'RequestInterceptor?'
A little bit cleaner look solution of Vishal Darvara asnwer for Alamofire 5 .
func uploadPhoto(_ url: String, image: UIImage, params: [String : Any], header: [String:String], completion: #escaping (JSON) -> ()) {
let httpHeaders = HTTPHeaders(header)
AF.upload(multipartFormData: { multiPart in
for p in params {
multiPart.append("\(p.value)".data(using: String.Encoding.utf8)!, withName: p.key)
}
multiPart.append(image.jpegData(compressionQuality: 0.4)!, withName: "avatar", fileName: "file.jpg", mimeType: "image/jpg")
}, to: url, method: .post, headers: httpHeaders) .uploadProgress(queue: .main, closure: { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}).responseJSON(completionHandler: { data in
print("upload finished: \(data)")
}).response { (response) in
switch response.result {
case .success(let resut):
print("upload success result: \(resut)")
case .failure(let err):
print("upload err: \(err)")
}
}
}
//swift 5
static func postComplexPictures(url:URL, params:[String:Any],pictures : UIImage, finish: #escaping ((message:String, list:[[String: Any]],isSuccess:Bool)) -> Void) {
var result:(message:String, list:[[String: Any]],isSuccess:Bool) = (message: "Fail", list:[],isSuccess : false)
let headers: HTTPHeaders
headers = ["Content-type": "multipart/form-data",
"Content-Disposition" : "form-data"]
AF.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
}
if let imageData = pictures.pngData() {
multipartFormData.append(imageData, withName: "document", fileName: "document.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers).response{ response in
if((response.error != nil))
{
do
{
if let jsonData = response.data
{
let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject>
print(parsedData)
let status = parsedData["status"] as? NSInteger ?? 0
let msg = parsedData["message"] as? String ?? ""
if(status==1)
{
result.isSuccess = true
result.message=msg
if let jsonArray = parsedData["data"] as? [[String: Any]] {
result.list=jsonArray
}
}
else
{
result.isSuccess = false
result.message=msg
}
}
finish(result)
}
catch
{
finish(result)
}
}
else
{
finish(result)
}
}
}

Upload multipart image with parameters in IOS

I am new to IOS n want to upload the image with parameters to server but it's not uploading. I tried a lot refer the alamofire and also base64 but nothing is working for me. Did I miss any thing, any help to understand this?
Thanks in advance. Please help me to resolve issue
Below is my code:
#IBAction func submitBtnClicked(_ sender: Any)
{
//parameters
var number: Int?
number = 47000482
var srNumber = String(format:"%d",number!)
var urlString: String = filePath!.absoluteString
var parameters = ["s_no":srNumber, "count":"1"]
let imgData = UIImageJPEGRepresentation(self.chosenImage!, 0.5)
print(parameters)
print(imgData)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData!, withName:"filestream", fileName:(self.filePath?.lastPathComponent)!, mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName:key)
}
}, to:"https://********************")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
//self.delegate?.showFailAlert()
print(encodingError)
}
}
}
//MARK: - Multiple Images Uploading API Call
func serviceUploadMultipleImageData(model : UploadImageResponseModel,isLoader:Bool = true,name:String = "", loaderViewcontoller : UIViewController? = nil,url: String, method: HTTPMethod, InputParameter: Parameters?, ServiceCallBack: #escaping (_ Completion: ServiceResponseNormal, _ isSuccess:Bool)-> Void) {
let viewContoller = loaderViewcontoller
guard Reachability.isConnectedToNetwork() else {
Singleton.sharedSingleton.showPopup(title: "No Internet", message: HttpCode.NoInternetConnection.message(), image: nil, VC: viewContoller!)
ServiceCallBack(self.setCustomResponse(Code: HttpCode.NoInternetConnection.rawValue, Message: "No Internet Connection"),false)
return
}
if isLoader == true {
if viewContoller != nil {
ProgressHUD.startLoading(onView: (viewContoller?.view)!)
} else {
ProgressHUD.startLoading(onView: appDelegate.window!)
}
}
Alamofire.upload(multipartFormData: { (multipartFormData) in
for obj in model.arrImages{
multipartFormData.append(obj.imageData!, withName:obj.imgName, fileName: "", mimeType: "image/jpg")
}
for (key, value) in InputParameter! {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)!, withName: key)
}
}, to:url)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
model.progress = Progress.fractionCompleted
})
upload.responseJSON { response in
if isLoader == true {
if viewContoller != nil {
ProgressHUD.stopLoading(fromView: (viewContoller?.view)!)
}else {
ProgressHUD.stopLoading(fromView: appDelegate.window!)
}
}
if(response.result.isSuccess){
print(response)
do{
if response.data != nil{
var responseParsed = try JSONDecoder().decode(ServiceResponseNormal.self, from: response.data!)
if responseParsed.Code == "200"
{
responseParsed.Data = response.data
ServiceCallBack(responseParsed, true)
}
else
{
Singleton.sharedSingleton.showPopup(title: "Error", message: responseParsed.Message ?? "Error", image: nil, VC: viewContoller!)
ServiceCallBack(responseParsed, false)
}
}
}
catch let error {
print(error.localizedDescription)
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = "Response could not parsed"
ServiceCallBack(falilure, false)
}
}
else{
if let error = response.result.error{
let message = error.localizedDescription
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = message
ServiceCallBack(falilure, false)
Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
}
}
}
case .failure(let encodingError):
let message = encodingError.localizedDescription
var falilure = ServiceResponseNormal()
falilure.Data = nil
falilure.Message = message
ServiceCallBack(falilure, false)
Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
}
}
}
Firstly you need to add method type i.e .post or .put type with along with url then you will able to send the image data and also increase the timeout interval for request of session manager.session.configuration.timeoutIntervalForRequest = 120 If you have any query you reply me on same So I will try to resolve your problem.
class func requestForAPI(param:Dictionary<String, String>?, Url:String,image:UIImage,isShowLoader:Bool, headers:[String:String]?, completion: #escaping (_ result: AnyObject?, _ error: Error?) -> Void) {
let reach:Reachability = Reachability.forInternetConnection()
let netStatus:NetworkStatus = reach.currentReachabilityStatus()
if (netStatus == NotReachable)
{
NSUtility.shared().showMessage(title: "Alert!", body: "Please connect to the internet to continue", themetype: .error)
return
}
if isShowLoader == true{
APPDELEGATE?.showLoaderView()
}
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
let imageData = image.jpegData(compressionQuality: 0.8)
manager.upload(multipartFormData:
{
(multipartFormData) in
multipartFormData.append(imageData, withName: "file", fileName: "file.jpeg", mimeType: "image/jpeg") for (key, value) in param {
multipartFormData.append(value.data(using:String.Encoding.utf8.rawValue)!, withName: key)
}, to:URL(string: Url)!,method:.put, headers:headers)
{ (result) in
switch result {
case .success(let upload,_,_ ):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON
{ response in
APPDELEGATE?.dismissLoader()
//print response.result
if response.result.value != nil
{
print (response.result.value as Any)
completion(response.result.value as AnyObject? , nil)
}
}
case .failure(let encodingError):
print(encodingError)
completion(nil, encodingError)
break
}
}}}

Alamofire multipart upload giving error

I am trying to upload an image to server using Alamofire Multipart Form data however upon execution iam getting error as
exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber
dataUsingEncoding:]: unrecognized selector sent to instance
0x1669e250'
in the line
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
below is my full code
guard let image = selectedImage else {
return
}
let heightInPixels = Int(image.size.height * image.scale)
let widthInPixels = Int(image.size.width * image.scale)
let parameters: Parameters = ["user_id": Utility().getBearerToken(),"description": descriptionTextView.text ?? "",
"lat": self.lat ?? "" , "long":self.long ?? "" ,
"location_name": locationTextView.text ?? "" ,
"height": heightInPixels, "width": widthInPixels];
// let parameters: Parameters = ["user_id": Utility().getBearerToken()];
print(parameters)
Alamofire.upload(multipartFormData: { MultipartFormData in
for (key, value) in parameters {
MultipartFormData.append(((value as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: key)
}
let imgData = UIImageJPEGRepresentation(image,1)
MultipartFormData.append(imgData!, withName: "file", fileName: "upload.jpg", mimeType: "image/jpeg")
}, to: "http://server.com/upload.php") { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseString { response in
print(response.result.value!)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
break
}
}
I tried with MultipartFormData.append(value.data(using: .utf8)!, withName: name!) but it says value has no member data
Try this below func, it is working.
func uploadImage(urlString : String , image : UIImage, param : [String : Any], completionHandler : #escaping ( _ result : Any?) -> ()) {
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
print("Could not get JPEG representation of UIImage")
return
}
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in param {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
multipartFormData.append(imageData,
withName: "image",
fileName: "image.jpg",
mimeType: "image/jpeg")
},
to: urlString,
headers: ["Authorization": "Basic xxx"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
}
upload.validate()
upload.responseJSON { response in
completionHandler(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
completionHandler(nil)
}
})
}
Here is the function for upload video and image with your other API Parameters.
func uploadWithAlamofire(Parameters params : [String: Any]?,ImageParameters imgparams : [NSObject : AnyObject]?,VideoParameters vidoparam : [NSObject : AnyObject]?,Action action : NSString, success: #escaping (AnyObject) -> Void, failure: #escaping (AnyObject) -> Void)
{
var base_url = BASEURL
base_url.append(action as String)
print(base_url)
var headers : HTTPHeaders = [:]
if let token = UserDefaults.standard.value(forKey: "webToken"){
headers = ["JWT-Authorization": "Bearer \(token)"]
}
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if vidoparam != nil{
for (key, value) in vidoparam! {
multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
var dictonary:NSDictionary?
if let data = responseString?.data(using: String.Encoding.utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] as NSDictionary?
if dictonary != nil{
if dictonary?.value(forKey: "status_code") as! String == "200"{
return success(dictonary!)
}else{
print(dictonary?.value(forKey: "status_code")! as Any)
let errorMsg : Any = Int(dictonary?.value(forKey: "status_code") as Any)
utility.showAlertWithStatusCode(code: errorMsg)
}
}
} catch let error as NSError {
print(error)
}
}
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}

Upload Photo / File with JSON and custom headers via Swift 3 and Alamofire 4 | iOS | Swift

I need to call the Multipart request with Image file and JSON.
I have tried this, but still getting the error.
// define parameters
let parameters = [
"hometown": "yalikavak",
"living": "istanbul"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append((value?.data(using: .utf8))!, withName: key)
}}, to: "upload_url", method: .post, headers: ["Authorization": "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
How to send the JSON?
Try This Code for Multiple upload Images in Single Request, This code is already working.
// For Pass Valid Parameters & number of Images in Array in Image Upload Function
var dicImgData : NSMutableDictionary? = NSMutableDictionary()
if let img = UIImage(named: "Your Image") {
if let data:Data = UIImagePNGRepresentation(img) {
var imageData : NSData = data
dicImgData! .setObject(imageData, forKey: "data" as NSCopying)
dicImgData! .setObject("file", forKey: "name" as NSCopying)
dicImgData! .setObject("file.png", forKey: "fileName" as NSCopying)
dicImgData! .setObject("image/png", forKey: "type" as NSCopying)
let dicParameter = [
"hometown": "yalikavak",
"living": "istanbul"
]
self.uploadImage(url: "Your URL", Parameter: dicParameter, Images: [dicImgData])
}
}
Upload Function
func uploadImage (url: String, Parameter param : NSDictionary, Images arrImage: NSArray) -> Void
{
var requestURL : String! = url
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json",
]
print("---------------------")
print("Request URL :- \(requestURL)")
print("---------------------")
Alamofire.upload(multipartFormData: { (data) in
for (key, value) in param {
data.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
for imageInfo in arrImage
{
var dicInfo : NSDictionary! = imageInfo as! NSDictionary
data.append(dicInfo["data"] as! Data, withName: dicInfo["name"] as! String, fileName: dicInfo["fileName"] as! String, mimeType: dicInfo["type"] as! String)
dicInfo = nil
}
}, to: requestURL, method: .post , headers:nil, encodingCompletion: { (encodeResult) in
switch encodeResult {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in
switch response.result
{
case .success(let responseJSON):
guard let dicResponse = responseJSON as? NSDictionary else{
return
}
print("Response : \((dicResponse))")
case .failure(let error):
print(error)
break
}
})
case .failure(let error):
print(error)
break
}
})
}
From data you have given, I comes to an conclusion as given below.
The status code 400 means json you're passing to the api was not following the api documentation. For example if they expect a key "name" and you're not given such a key at all.
Other possible reasons for this error.
Seems like you haven't mentioned any of content types
Add these line of code to assure that the response and your request are in proper formats
Alamofire.request(.GET, "your url", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { (_, _, _, error) in
println(error)
}
The Accept header tells the server what your client wants in the
response. The Content-Type header tells the server what the client
sends in the request.
If you can give more information we can help further.
Here I made my custom webservice, You can use it. This webservice is for upload dictionary with image and video or both or without it.
import Foundation
import Alamofire
class WebServiceHandler: AnyObject {
func uploadWithAlamofire(Parameters params : [NSObject : AnyObject]?,ImageParameters imgparams : [NSObject : AnyObject]?,VideoParameters vidoparam : [NSObject : AnyObject]?,Action action : NSString, success: #escaping (AnyObject) -> Void, failure: #escaping (AnyObject) -> Void)
{
var base_url = "http://benzatineinfotech.com/webservice/finder/index.php/Web_api/"
base_url.append(action as String)
Alamofire.upload(multipartFormData: { multipartFormData in
if imgparams != nil{
for (key, value) in imgparams! {
if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) {
multipartFormData.append(imageData, withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000)).jpg", mimeType: "image/jpg")
}
}
}
if vidoparam != nil{
for (key, value) in vidoparam! {
multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
}
}
if params != nil
{
for (key, value) in params! {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
}
} }, to: base_url, method: .post, headers: nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
print(progress.fractionCompleted)
}
upload.response { [weak self] response in
guard self != nil else {
return
}
let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
return success(responseString as AnyObject)
}
case .failure(let encodingError):
print("error:\(encodingError)")
return failure(encodingError as AnyObject)
}
})
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
Usage:
self.webservice.uploadWithAlamofire(Parameters: dict_params as [NSObject : AnyObject], ImageParameters: imgparam as [NSObject : AnyObject], VideoParameters: videoparam as [NSObject : AnyObject], Action: "write_message", success: { (success) in
print(success)
}) { (error) in
print(error)
}

Resources