Search code examples
iosswiftnetwork-programmingalamofire

How to detect upload progress and upload status in Alamofire 5 with Swift?


In document of alamorefire, It have only this example for detect a upload progress

AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(Data("one".utf8), withName: "one")
    multipartFormData.append(Data("two".utf8), withName: "two")
}, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
        debugPrint(response)
}

But my expectation is I want to detect its upload progress and upload status after it done like some result

switch result {
    case .success():
       //Success code
       break

    case .failure:
       //show error upload failed
       break
}

Solution

  • 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)")
                 }
            }