首页 > 解决方案 > 如何在多个视图中使用来自单例的一个回调

问题描述

如何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{}

    }

}

标签: iosswiftsingleton

解决方案


第 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")
    }

有关闭包的更多详细信息,请访问以下链接。 闭包


推荐阅读