Progress of a Alamofire request
The way you monitor progress in Alamofire is using the progress
closure on a Request
. More details on usage can be found in the README. While that example in the README demonstrates usage on a download request, it still works on a data request as well.
The one important note is that you do not always get perfect reporting back from the server for a data request. The reason is that the server does not always report an accurate content length before streaming the data. If the content length is unknown, the progress closure will be called, but the totalExpectedBytesToRead
will always be -1
.
In this situation, you can only report accurate progress if you know the approximate size of the data being downloaded. You could then use your approximate number in conjunction with the totalBytesRead
value to compute an estimated download progress value.
Alamofire POST request with progress
What you can do instead is first use the ParameterEncoding
enum to generate the HTTPBody data. Then you can pull that data out and pass it off to the Alamofire upload
method. Here's a modified version of your same function that compiles in a playground and instead uses the upload
function.
struct ApiLink {
static let create_post = "/my/path/for/create/post"
}
let parameters: [String: AnyObject] = ["key": "value"] // Make sure this has your image as well
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: ApiLink.create_post)!)
mutableURLRequest.HTTPMethod = Method.POST.rawValue
let encodedURLRequest = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
let data = encodedURLRequest.HTTPBody!
let progressView = UIProgressView()
Alamofire.upload(mutableURLRequest, data)
.progress { _, totalBytesRead, totalBytesExpectedToRead in
println("ENTER .PROGRESSS")
println("\(totalBytesRead) of \(totalBytesExpectedToRead)")
progressView.setProgress(Float(totalBytesRead) / Float(totalBytesExpectedToRead), animated: true)
}
.responseJSON { _, _, mydata, _ in
println(mydata)
}
This will certainly have progress updates as @mattt originally mentioned in his comment above.
How to detect upload progress and upload status in Alamofire 5 with Swift?
try this :-
AF.upload(multipartFormData: { MultipartFormData in
MultipartFormData.append(fileContent, withName: "file" , fileName: filePath.lastPathComponent , mimeType: "image/jpeg")
for(key,value) in dictonary {
MultipartFormData.append(token.data(using: String.Encoding.utf8)!, withName: "token")
}
}, to: uploadURL, method: .post, headers: ["Content-Type": "application/json")
.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
.responseJSON{ (response) in
debugPrint("SUCCESS RESPONSE: \(response)")
}
}
Alamofire Progress status showing 0.0 in some URL cases using swift ios
The HTTP Header Content-Length
is required to determine the progress. Alamofire knows the size of data received, but to show the progress it need the total Content-Length
Here i've prepared a sample test. I will compare two site
- https://www.cocoacontrols.com
- https://www.stackoverflow.com
First one have no Content-Length
in their responses, but second one have.
Use CURL
to check the HTTP Headers.
curl -I https://www.cocoacontrols.com
...
... // there is no content length header in this output.
...
curl -I https://www.stackoverflow.com
...
content-length: 149
...
Sample test.
func sampleTest(link: String) {
let url = URL.init(string: link)!
Alamofire.request(url,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: nil)
.downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
print("TEST Progress: \(progress.fractionCompleted)")
}
.validate { _, _, _ in
return .success
}
.responseData { response in
print("repsonse received")
}
}
Now calling this method as followings
Test #1
sampleTest(link: "https://www.cocoacontrols.com")
Output #1
TEST Progress: 0.0
TEST Progress: 0.0
TEST Progress: 0.0
TEST Progress: 0.0
Test #2
sampleTest(link: "https://www.stackoverflow.com")
Output #2
TEST Progress: 0.0
TEST Progress: 0.0
TEST Progress: 0.8040637101235478
TEST Progress: 1.0
Hope it helps understands your problem of missing the Content-Length
HEADER in your HTTP response. For further reference, even there is a github issue in Alamofire repository, facing the same problem, solved by adding the Content-Lenght
header adding in the response HEADER field.
Alamofire upload progress
Maybe your file is too small, try a larger file.
Related Topics
How to Add Pagination in UItableview.
Data Repeat in UItableview When Scrolling
Can Someone Explain This @Synthesize Syntax
Scenekit Flattenedclone - Incorrect Use of Objc_Storeweak() and Objc_Loadweak() Error
Uiviewrepresentable Automatic Size - Passing UIkit UIview Size to Swiftui
How to Make a Synchronous Request Using Alamofire
Auto Layout How to Hide 1 View in a View with 3 Equal Width Views
How to Prevent Duplicates in Realmswift List
Center Swiftui View in Top-Level View
Swift Correct Use of Getters and Setters
iOS Uitableview Accessibility Order Is Wrong After Setting Accessibilityelements on Uitableviewcell
Converting String to Nsdate Giving Wrong Date
Mpvolumeview Does Not Show Route Button on Launch
Adding an Skscene to a Uiviewcontroller
Uitabbar Change Background Color of One UItabbaritem on iOS7