美文网首页
Alamofire 文件下载

Alamofire 文件下载

作者: 西风那个吹呀吹 | 来源:发表于2022-09-01 12:32 被阅读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

    相关文章

      网友评论

          本文标题:Alamofire 文件下载

          本文链接:https://www.haomeiwen.com/subject/qtfsnrtx.html