问题
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.
Errors getting on init(webService: DataProvider = DataProvider())
:
'self' used before 'super.init' call
'super.init' isn't called on all paths before returning from initializer
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
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()
})
回答1:
You should call super.init()
before using self object so that properties of base class are initialized before using self.
来源:https://stackoverflow.com/questions/59764565/how-to-set-protocol-function-not-properly-invoke-in-dataprovider-class-alamofire