ios - 如何在多个视图中使用来自单例的一个回调
问题描述
如何onCompleted
在多个类视图中使用。
更新完整代码!!!
import Foundation
import Alamofire
class AudioSyncManager {
//var onDownloadStart: (()->())?
var onDownloadFinished: ((_ isSuccess: Bool)->())?
var onDownloadProgress: ((_ progress: Float)->())?
static let shared = AudioSyncManager()
private var downloadRequest: DownloadRequest?
private var isDownloading = false
var listData: [MainModel] = []
func doDownloding(onStarted: @escaping ()->()) {
if listData.count == 0 || isDownloading {
return
}
let firstModel = listData.first
if checkMp3FileExists(model: firstModel!) {
self.isDownloading = false
self.listData.removeFirst()
if self.listData.count > 0 {
self.doDownloding {}
}
return
}
let mp3URLString = MyHelper.MEDIA_URL_PREFIX + (firstModel?.link)!
let url = URL(string: mp3URLString)
let destination = DownloadRequest.suggestedDownloadDestination(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)
//isDownloading = true
onStarted()
downloadRequest = Alamofire.download(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil, to: destination)
.downloadProgress { (progress) in
self.onDownloadProgress?(Float(progress.fractionCompleted))
}.response { (response) in
self.isDownloading = false
self.onDownloadFinished?(true)
if self.listData.count > 0 {
self.listData.removeFirst()
}
if self.listData.count > 0 {
self.doDownloding{}
}
}
}
func addSingleTask(mainModel: MainModel) {
listData.append(mainModel)
doDownloding{}
}
func addListTask(newList: [MainModel]) {
listData.append(contentsOf: newList)
doDownloding{}
}
}
解决方案
第 1 点
您应该在下面的行中收到错误
let static shared = Service()
因为 static 关键字应该首先出现然后声明。
static let shared = Service()
第 2 点
使用 Completion Handler 实现 onDownload 函数
func doDownload(onCompleted: @escaping ()->()) {
onCompleted()
}
调用如下函数
let service = Service.shared
service.doDownload { () in
print("Called in completion Handler")
}
有关闭包的更多详细信息,请访问以下链接。 闭包
推荐阅读
- flutter - 错误:未为“对象”类型定义运算符“[]”注意!请检查图片是否包含错误
- mariadb - 如果不存在,则强制 mysqldump 使用 CREATE DATABASE
- c# - 为什么 F# 代码产生与 C# 不同的结果
- javascript - 如何在对象数组的 id 数组中找到一个 id?
- reactjs - 如何正确检查 router.query.param 是字符串还是 [] 字符串?
- shell - 如何从本地终端在 Google colab 中启动(打开并运行).ipynb 文件?
- python - 带数字的星号金字塔
- javascript - 从 CodePipeline 调用 Lambda 以使 CloudFront 缓存无效
- arrays - 在遍历数组并在 vue 中使用 [current_element + 1] 时无法访问下一个元素?
- google-bigquery - 将 Google Cloud Storage 中的多个 csv 加载到 BigQuery 中的多个表中