【问题标题】:How can I create protocol delegate to observe Alamofire progress and to use in ViewController swift如何创建协议委托以观察 Alamofire 进度并在 ViewController swift 中使用
【发布时间】:2020-05-02 07:25:20
【问题描述】:

如何在Alamofire 下载函数中创建协议(委托函数)来观察progress.fraction 然后我可以在任何viewController tableView 中使用它?

我的Alamofire 函数在主要公共类中,我必须检索文件下载的进度值。

Alamofire 下载功能

@objc public func downloadFile(url:String, filetype: String, callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
        var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
        if filetype.elementsEqual(".pdf"){
            destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let downloadFileName = url.filName()
                let fileURL = documentsURL.appendingPathComponent("\(downloadFileName).pdf")
                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }
        } 

        Alamofire.download(
            url,
            method: .get,
            parameters: nil,
            encoding: JSONEncoding.default,
            headers: nil,
            to: destination).downloadProgress(closure: { (progress) in
                //progress closure
                print(progress.fractionCompleted)

            }).response(completionHandler: { (DefaultDownloadResponse) in
                callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.absoluteString.replacingOccurrences(of: "file://", with: ""))
                print(DefaultDownloadResponse)
            })
    }

【问题讨论】:

    标签: swift uitableview uiviewcontroller alamofire uiprogressview


    【解决方案1】:

    类似这样的:

    protocol MyWebServiceProtocol: class {
       func progress(_ fractionCompleted: Int)
       func downloadDidSucceed(data: Data)
       func downloadDidFail(error: Error)
    }
    
    class MyViewController: UIViewController {
    
        let webService: MyWebService
    
        init(webService: MyWebService = MyWebService()) {
            self.webService = webService
            super.init(nibName: nil, bundle: nil)
            self.webService.delegate = self
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    
    }
    
    extension MyViewController: MyWebServiceProtocol {
        func progress(_ fractionCompleted: Int) {
           print(fractionCompleted) // do something with progress
        }
    
        func downloadDidSucceed(data: Data) {
             // Do something here
        }
    
        func downloadDidFail(error: Error) {
            // handle error
        }
    }
    
    class MyWebService {
    
        weak var delegate: MyWebServiceProtocol?
    
        @objc public func downloadFile(url:String, filetype: String, callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
            var destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
            if filetype.elementsEqual(".pdf"){
                destination = { _, _ in
                    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                    let downloadFileName = url.filName()
                    let fileURL = documentsURL.appendingPathComponent("\(downloadFileName).pdf")
    
                    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }
        } 
    
        Alamofire.download(
            url,
            method: .get,
            parameters: nil,
            encoding: JSONEncoding.default,
            headers: nil,
            to: destination).downloadProgress(closure: { [weak self] (progress) in
                //progress closure
                self?.delegate?.progress(progress.fractionCompleted)
                print(progress.fractionCompleted)
    
            }).response(completionHandler: { [weak self] (DefaultDownloadResponse) in
                callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.absoluteString.replacingOccurrences(of: "file://", with: ""))
                self?.delegate?.downloadDidSucceed()
                print(DefaultDownloadResponse)
            })
    }
    

    【讨论】:

    • 我试图实现它,但得到一个错误。你能检查一下吗? stackoverflow.com/questions/59764565/…
    • 现在在fatalError 它给了我错误Fatal error: init(coder:) has not been implemented: file /Users/macuser/Documents/XCodeWork/ABC/ABC/ViewControllers/DownloadViewController.swift
    • 构建在运行时生成的错误之上很好。
    • 这是纯 Swift 类视图控制器还是 nib?
    • 如果您创建的视图控制器没有指向 nib 的链接,它将起作用。如果您连接了 nib 文件,则此初始化将不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多