Search code examples
iosswiftalamofire

Alamofire Progress status showing 0.0 in some URL cases using swift ios


CODE:

Alamofire.request(URL(string: imageUrl)!).downloadProgress(closure: { (progress) in

            DispatchQueue.main.async {
                print(progress.fractionCompleted)
                successCallback(progress.fractionCompleted as Double)

            }

        }).responseData { (response) in
            print(response.result)
            completionCallback(response as DataResponse)

            switch response.result {
            case .success(let responseJSON):
                print(responseJSON)
            case .failure(let error):
                failureCallback(error.localizedDescription)
            }
        }

Solution

  • 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

    1. https://www.cocoacontrols.com
    2. 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.