ios - 如何在 DataProvider 类 Alamofire 函数 swift 中设置协议(protocol)函数未正确调用

标签 ios swift delegates alamofire protocols

我需要在Alamofire下载功能中设置协议(protocol)功能来跟踪和观察进度分数值。我必须尝试实现委托(delegate)函数,但它无法正确执行并给出错误。我有一个具有 Alamofire 函数的 DataProvider 类,然后我在 ViewController 中调用它。

init(webService: DataProvider = DataProvider()) 出错:

'self' used before 'super.init' call
'super.init' isn't called on all paths before returning from initializer

View Controller 代码:

let webService: DataProvider

    init(webService: DataProvider = DataProvider()) {
        //super.init()
        self.webService = webService
        self.webService.delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

extension DownloadViewController: MyWebServiceProtocol {
    func progress(_ fractionCompleted: Double) {
        print(fractionCompleted)
    }

    func downloadDidSucceed() {
        print("download")
    }


    func downloadDidFail(error: Error) {
        // handle error
    }
}

DataProvider.Class

protocol MyWebServiceProtocol: class {
   func progress(_ fractionCompleted: Double)
   func downloadDidSucceed()
   func downloadDidFail(error: Error)
}

// in class
weak var delegate: MyWebServiceProtocol?

//Alamofire

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

                print(progress.fractionCompleted)
            }).response(completionHandler: { (DefaultDownloadResponse) in
                //here you able to access the DefaultDownloadResponse
                //result closure
                callback(DefaultDownloadResponse.response?.statusCode == 200, DefaultDownloadResponse.destinationURL?.absoluteString.replacingOccurrences(of: "file://", with: ""))
                print(DefaultDownloadResponse)
                self.delegate?.downloadDidSucceed()
            })

最佳答案

在使用 self 对象之前应该调用 super.init() ,以便在使用 self 之前初始化基类的属性。

关于ios - 如何在 DataProvider 类 Alamofire 函数 swift 中设置协议(protocol)函数未正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764565/

相关文章:

objective-c - 如何在 Objective C 中创建委托(delegate)者?

ios - 委托(delegate)不发回对象

ios - Xcode 6.3 更新导致 ide 卡住并需要强制退出

ios - 为什么我的代码仅在发布时和升级到 Xcode 4.6 后崩溃?

swift - 如何计算 SKScenes

Swift for in 带括号的循环

ios - 网络任务 iOS 的 GCD

iphone - 在 UITextField 中添加按钮

ios - subview 未添加某些 UICollectionViewCells 并闪烁(以编程方式)

iphone - 子类化委托(delegate)?