使用NotificationCenter的加载程序

时间:2018-06-20 08:35:44

标签: ios swift

我有代码:

MainView.swift:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        // Register to receive notification
        NotificationCenter.default.addObserver(self, selector: #selector(MainViewControler.StartUpdatingSplash), name: NSNotification.Name("StartUpdatingSplashNotificationName"), object: nil)

        //new code
        NotificationCenter.default.addObserver(self, selector: #selector(MainViewControler.FinishUpdatingSplash), name: NSNotification.Name("FinishUpdatingSplashNotificationName"), object: nil)

    }

    @objc func StartUpdatingSplash() {
        DispatchQueue.global().async {
            EZLoadingActivity.show("LoadingMessage4".localized(), disableUI: true)
        }
        print("##### NOTIFICATION STEP: 1")
    }

    @objc func FinishUpdatingSplash() {
        DispatchQueue.global().async {
            EZLoadingActivity.hide()
        }
        // Stop listening notification
        NotificationCenter.default.removeObserver(self, name: Notification.Name("StartUpdatingSplashNotificationName"), object: nil)
        print("##### NOTIFICATION FINISH STEP: 2")
    }

App.swift:

var filesToDownload = [FilesToDownload]()
var filesToDownloadPDF = [FilesToDownload]()

struct FilesToDownload {
    var fileInternetUrl: String?
    var fileName: String?
    var savedURL: String?
    var productImageUrl: URL?
    var fileSize: Int
}    

func startDownloadFiles(filesArray: [FilesToDownload], filesType: Int){
        // Post notification
        NotificationCenter.default.post(name: Notification.Name("StartUpdatingSplashNotificationName"), object: nil)
        for files in filesArray{
            if filesType == 1 {
                print ("PLIKI DO SCIAGNIECIA: \(files)")
                checkRemoteImage(fileInternetUrl: files.fileInternetUrl!, fileName: files.fileName!, savedURL: files.savedURL!, productImageUrl: files.productImageUrl!, fileSize: files.fileSize)
            } else {
                print ("PLIKI DO SCIAGNIECIA PDF: \(files)")
                checkRemotePdf(fileInternetUrl: files.fileInternetUrl!, fileName: files.fileName!, savedURL: files.savedURL!, productPdfUrl: files.productImageUrl!, fileSize: files.fileSize)
            }
        }
    }

func checkRemoteImage(fileInternetUrl: String, fileName: String, savedURL: String, productImageUrl: URL, fileSize: Int){
        remoteResource(at: productImageUrl, fileSize: fileSize) { (isImage) in
            if isImage == true {
                self.saveDownloadFiles(fileInternetUrl: productImageUrl, fileName: fileName, savedURL: savedURL)
            }
        }
    }

    func checkRemotePdf(fileInternetUrl: String, fileName: String, savedURL: String, productPdfUrl: URL, fileSize: Int){
        self.saveDownloadFiles(fileInternetUrl: productPdfUrl, fileName: fileName, savedURL: savedURL)
    }


    func saveDownloadFiles(fileInternetUrl: URL, fileName: String, savedURL: String){
        let cms = ServerConnect()
        cms.downloadedFileFromInternet(fileInternetUrl: fileInternetUrl, directory: savedURL, fileName: fileName ,  completion: { (data) in
            switch data {
            case .succes:
                print("DOWNLOAD: \(savedURL)/\(fileName)")
            case .error(let error):
                //self.errorLoginMessage(txt: "MainView - Error 110: Problem with download images. \(error)", title: "Blad".localized())
                print("")
                break
            }
        })
    }


func downloadedFileFromInternet(fileInternetUrl: URL, directory: String, fileName: String , completion: @escaping completionHandler) {
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileURL = dir.appendingPathComponent(directory)

            if !FileManager.default.fileExists(atPath: fileURL.path) {
                do {
                    try FileManager.default.createDirectory(atPath: fileURL.path, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    NSLog("Couldn't create document directory")
                }
            }
            do {
                let data = try? Data(contentsOf: fileInternetUrl)
                try data?.write(to: fileURL.appendingPathComponent(fileName), options: .atomic)
            } catch let error {
                print("Error : \(error.localizedDescription)")
            }

        } 
    }

在功能startDownloadFiles中,我开始下载文件。 我要在文件下载(EZLoadingActivity)时显示加载程序。

当前,启动启动程序(loader EZLoadingActivity)应用程序后,启动程序始终可见,下载所有文件后它不会隐藏。

从文件EZLoadingActivity下载所有文件后,如何隐藏这些FileToDownload / filesToDownloadPDF

1 个答案:

答案 0 :(得分:3)

您可以在以下完成内容中触发通知

URLSession.shared.dataTask(with: fileUrl) { (data, response
        , error) in
    NotificationCenter.default.post(name: Notification.Name("FinishUpdatingSplashNotificationName"), object: nil)
}

我注意到您正在拨打电话的其他几个地方。因此,如果在使用这些方法发出请求之前显示了加载程序,则也应该在该位置触发此通知。例如,

PromiseKit

然后在您的侦听器方法中,您应该有逻辑知道是否是隐藏加载程序的正确时间。

建议:使用通知不是处理您要处理的内容的好方法。这将为您管理比赛条件增加很多精力。我建议您检查completion handlers或至少有效使用</client> <serviceHostingEnvironment multipleSiteBindingsEnabled="false" aspNetCompatibilityEnabled="true"/> <bindings> <!-- this for restfull service --> <webHttpBinding> <binding name="RestfullwebHttpBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" /> </binding> </webHttpBinding> <!-- end --> <!-- this for Soap v.2 --> <wsHttpBinding> <binding name="wsBinding1" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/> <!--UsernameToken over Transport Security--> <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" establishSecurityContext="true"/> </security> </binding> </wsHttpBinding> <!-- this for restfull service --> <!-- this for Soap v.1 --> <basicHttpBinding> <binding name="basicBinding1" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false" transferMode="Streamed"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> <security mode="None"/> </binding> </basicHttpBinding> </bindings> <!-- end --> <services> <clear/> <service name="ING.IWCFService.CitisecHashTransfer" > <endpoint address="http://localhost:8099/CitisecHashTransfer.svc" behaviorConfiguration="RestfullEndpointBehavior" binding="webHttpBinding" bindingConfiguration="RestfullwebHttpBinding" name="ICitisecHashTransferBasicHttpBinding" contract="ING.IWCFService.ICitisecHashTransfer" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpsGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ING.IWCFService.IWCFServiceValidator, ING.IWCFService"/> </serviceCredentials> <serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="SuccessOrFailure" messageAuthenticationAuditLevel="SuccessOrFailure"/> <serviceThrottling maxConcurrentCalls="1000" maxConcurrentSessions="100" maxConcurrentInstances="1000"/> </behavior> <behavior> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="EndpointBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> <behavior name="RestfullEndpointBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <webHttp/> </behavior> </endpointBehaviors> </behaviors>