Alamofire 文件下载

2022-09-01  本文已影响0人  西风那个吹呀吹

第一种:

AF.download(urlString, headers: headers).downloadProgress { speed in
                downloadProgress(speed.fractionCompleted)
            }.responseData { response in
                switch response.result {
                case .success(let json):
                    success(json)
                case .failure(let errMsg):
                    print("下载失败 :\(errMsg)")
                    failure("下载失败~")
                }
            }

第二种:

// Stream 无法获取下载进度
            var totalData: Data = Data()
            AF.streamRequest(urlString, headers: headers).responseStream { stream in
                switch stream.event {
                    case let .stream(result):
                        switch result {
                            case let .success(data):
                            totalData.append(data)
                                print("下载--:", data, totalData)
                            case let .failure(msg):
                                print("下载失败--:", msg)
                                failure("下载失败")
                            }
                    case let .complete(completion):
                        print("下载完成--:", completion)
                        success(totalData)

                }
            }

第三种:

AF.request(urlString, method: .get, headers: headers).responseData { response in
                switch response.result {
                case let .success(data):
                    success(data)
                case .failure(_):
                    failure("下载失败~")
                }
            }.downloadProgress { ppp in
                downloadProgress(ppp.fractionCompleted)
            }

第一种和第三种,在downloadProgress回调里fractionCompleted属性一直为零,是因为响应头没有Content-Length,导致Alamofire无法计算下载进度,让服务端开发人员加上即可。
可以多了解下 Content-Length Transfer-Encoding:chunked

上一篇下一篇

猜你喜欢

热点阅读