This question already has answers here:
Progress of a Alamofire request
(3 answers)
Closed 3 years ago.
I wanna know it is possible to show progress for request. I convert my images to base64 string and send it to my server with parameter. Is there a way to track it's progress? I wanna try something like that.But I cannot add progress section in my Alamofire.request. Is there something that I am missing?
Alamofire.request(.POST, URL, parameters: parameter, encoding: .JSON)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
// track progress here
}
.responseJSON { response in
// Do your stuff
}
Not sure but I think the current version of Alamofire uses downloadProgress instead of progress:
Alamofire.request(/* ... */).downloadProgress { progress in
progress.fractionCompleted // value between 0 and 1
}
.responseJSON { /* ... */ }
You can do like this
Alamofire.upload(multipartFormData: { (multipartFormData) in
}, with: URL, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
// Here you get the progress
print(Progress.fractionCompleted)
})
upload.responseJSON { response in
case .failure( _ ):
}
})
Related
This question already has answers here:
post application/x-www-form-urlencoded Alamofire
(3 answers)
Closed 2 years ago.
I'm trying to parse a JSON from a post request but I need to pass the content as x-www-form-urlencoded. I'm using Alamofire and Swift5, the code used to perform the request is this:
public func performRequest(url: String, parameters: [String:String]){
AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).validate().responseJSON{ response in
switch response.result {
case .success(let JSON): // memorizza il file JSON di risposta in una variabile di nome JSON
print("Validation Successful with response JSON \(JSON)")
case .failure(let error):
// print(error.localizedDescription)
print("Request failed with error \(error)")
}
}
}
How do I pass the content as x-www-form-urlencoded?
You can achieve it to adding in header like :
let param:Parameters=[
"param":param]
let headers:HTTPHeaders=[
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"]
Alamofire.request(url,method: .post,parameters: param,encoding: URLEncoding.httpBody, headers: headers).responseJSON{response in
....
}
I would like to show a progress bar for one of the web API call in ios app.Instead of showing only activity indicator to the user untill the web service is completed, showing him the status of progress is user friendly.I have seen many examples showing the progress bar with the user defined time but those are not related to WEB api call time duration. So can anyone guide me to do the above task ?
// like iam using SVProgress for uplaod an image
// for showing Progress iam getting Progress.fractionCompleted from uploadProgress
eg:-
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(data!, withName: "media", fileName: "media.jpeg", mimeType: "media/jpeg")
for (key, value) in parameters! {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, to:baseUrl,headers:parameters)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
SVProgressHUD.showProgress(Float(Progress.fractionCompleted))
})
upload.responseJSON { response in
//self.delegate?.showSuccessAlert()
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
SVProgressHUD.dismiss()
// Hope its works for you..
upload(urlRequest.1, with: urlRequest.0)
Progress {(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in // Error Comes Here
print("\(Int64(totalBytesWritten)) / \(Int64(totalBytesExpectedToWrite))")
}
.responseJSON
{
response in
hideLoading()
showToast("Profile Updated Successfully!!")
}
The problem is that you've replaced .uploadProgress with Progress, but have not changed the three parameters to the closure to be the single Progress parameter.
When you call .uploadProgress, the first parameter to that closure is a Progress (formerly known as NSProgress). But the Alamofire method name, uploadProgress, is unchanged. Only the parameters to the closure have changed.
Thus you want something like:
Alamofire.upload(data, with: request)
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
self.hideLoading()
switch response.result {
case .failure(let error):
self.showToast("Problem uploading: \(error.localizedDescription)")
case .success:
self.showToast("Profile Updated Successfully!!")
}
}
Bottom line, the upload progress method is called uploadProgress, and it takes one parameter, a NSProgress/Progress object.
I am trying to upload using alamofire, I am using the following code:
Alamofire.upload(urlRequest.0, to: urlRequest.1, method: .put)
.uploadProgress(queue: DispatchQueue.utility) { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
//Some code here
}
Where urlRequest is a tuple: (URLConvertible, Data). I am getting the compiler error : "Ambiguous reference to member 'upload(_:to:method:headers:)'". Any ideas what I am doing wrong here? Any pointers would be really appreciated! Thanks!
You may need to add the headers parameter:
Alamofire.upload(urlRequest.0, to: urlRequest.1, method: .put, headers: nil)
.uploadProgress { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}
while a tuple's types should stand in this order: (Data, URLConvertible)
I'm unable to approach the API that has been offered to me in the proper way for it to give me the response I'm looking for. I've been using Swift and Alamofire for a while but this is the first time I've to upload images using multipart/form-data. I'm able to upload images using Postman but I'm unable to get the same message send out by my application using the Alamofire framework.
My Swift code:
func postFulfilWish(wish_id: Int, picture : UIImage, completionHandler: ((AnyObject?, ErrorType?) -> Void)) {
var urlPostFulfilWish = Constant.apiUrl;
urlPostFulfilWish += "/wishes/";
urlPostFulfilWish += String(wish_id);
urlPostFulfilWish += "/fulfill/images" ;
let image : NSData = UIImagePNGRepresentation(UIImage(named: "location.png")!)!
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
//This is where the code ends up now
//So it's able to encode my message into multipart/form-data but it's not doing it in the correct way for the API to handle it
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
In case it is not already answered, recently I had the same problem using Alamofire to upload an Image using form-data.
I was able to upload the image using Postman exactly as it's shown in this post, but no able to do it using Alamofire in my app.
You need to check two things, first of all, the name of the file that the server is expecting, and second the method used to append the body part in the multipartFormData closure.
This two methods were not working in my case -
multipartFormData.appendBodyPart(data: imageData, name: "file")
this one neither
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: name)
But on this one worked splendid -
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
The problem basically is that the server can't find the file with the expected name.
I hope this help someone to save time wondering why it's not working.
You are doing debugPrint(response). You presumably should do another switch response.result { ... } and see if you got .Success or .Failure as the result of the request, and if success, you'd look at the response object contents (or if failure, look at the failure error). You need to look at that result to diagnose whether it was successful or not.
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .Success(let value):
print(value)
case .Failure(let error):
print(error)
}
}
case .Failure(let encodingError):
print(encodingError)
}
}
I recently got a 404 from the server when posting a multipart request along with parameters in the body. I was using a UIImagePickerController (the delegate for which returns a UIImage) and I then sent up the PNG representation of it.
This only occurred for files that were JPEG on disk. Strangely this issue seems to only affect multipart requests that also had parameters in the body. It worked fine when the API endpoint didn't require anything else.
My guess is that there is something weird going on along the line of JPEG -> UIImage -> PNG representation that results in some sort of problem which oddly only seems to manifest itself in multipart requests that also have parameters in the body. Might be some special characters in there that makes the server not recognise the request and just return a 404.
I ended up fixing it by sending up the UIImageJPEGRepresentation of the selected image instead of UIImagePNGRepresentation, and no such errors.
I believe the question is outdated already but for as long as there is no answer accepted try the following:
multipartFormData.appendBodyPart(data: imageData, name: "name", fileName: "filename", mimeType: mimeType)