如何设置协议函数无法在DataProvider类中正确调用Alamofire函数swift [英] how to set protocol function not properly invoke in DataProvider class Alamofire function swift

查看:139
本文介绍了如何设置协议函数无法在DataProvider类中正确调用Alamofire函数swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to set protocol function in Alamofire download function to track and observe progress fraction value. I have to tried to implement delegate function but its not properly executes giving error. I have one DataProvider class which has Alamofire function and then I am calling this in ViewController.

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

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

ViewController代码:

ViewController Code:

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

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()
            })


推荐答案

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

You should call super.init() before using self object so that properties of base class are initialized before using self.

这篇关于如何设置协议函数无法在DataProvider类中正确调用Alamofire函数swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆