如何在使用文件管理器创建文件时在 UI 中显示 Activity 指示器

How to show Activity Indicator in UI, while creating file Using File Manger

我正在从远程服务器下载文件(.pdf、.JPG、.PNG 等)。 "fullFileURLString" 是在字符串中提供文件路径 URL。

当用户从 collection 视图中单击文件名时,我需要提供将文件保存在用户自己的设备中的选项。为此,我正在使用 UIDocumentInteractionController()。我计划将此功能提供给用户。

此功能运行正常。这个过程需要一些时间来完成。我想在此过程发生时显示 Activity 指示器。但是 Activity 指示器没有动画或没有显示在视图中。

如何在这个过程发生时显示 Activity 指示器并在存在 documentInteractionController 时隐藏 activity 指示器?

我试过下面的代码

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"showUplodedMediaCellCollectionViewCell", for: indexPath) as! showUplodedMediaCellCollectionViewCell;
        if let bytes = Memory().deviceRemainingFreeSpaceInBytes() {
            let twoHundresMb:Int64 = 283115520
            if bytes < twoHundresMb {
                Alert.showAlertView(on: self, message: "There is not enough available storage to download.")
            }
            else {
                let activityIndicatior:UIActivityIndicatorView = UIActivityIndicatorView()
                activityIndicatior.center = self.view.center
                activityIndicatior.hidesWhenStopped = true
                activityIndicatior.style = .gray
                view.addSubview(activityIndicatior)
                activityIndicatior.startAnimating()
                let mediaDetails = MediaFiles?[indexPath.row]
                if let path = mediaDetails?.folderPath {
                    if let Filename = mediaDetails?.name {
                     let fullFileURLString = "\(baseURL)"+"\(path)"+"\(Filename)"
                        if let FileUrl = URL(string: fullFileURLString) {
                            let Filedata = try? Data(contentsOf: FileUrl)
                            let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
                            let documentDirectoryPath2 = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
                            let documentDirectoryPathURL = NSURL(fileURLWithPath: documentDirectoryPath)

                            if let pathComponent = documentDirectoryPathURL.appendingPathComponent(Filename) {
                                let fileManager = FileManager.default
                                let filePath = pathComponent.path
                                if fileManager.fileExists(atPath: filePath) {
                                    print("Already Have:",Filename)
                                }
                                else {
                                    print("No available",Filename)
                                    let fileManager = FileManager.default
                                    let fileManagerPath = documentDirectoryPath2.appendingPathComponent(Filename)
                                    fileManager.createFile(atPath: fileManagerPath, contents: Filedata, attributes: nil)
                                    print("path:- \(fileManagerPath)")
                                }
                            }

                            let destinationPath = documentDirectoryPath2.appendingPathComponent(Filename)
                            let destinationURL = URL(fileURLWithPath: destinationPath)
                            let dowanloadedMediaDocumentDirectoryPathURL = NSURL(fileURLWithPath: documentDirectoryPath)

                            if let pathComponent = dowanloadedMediaDocumentDirectoryPathURL.appendingPathComponent(Filename) {
                                let fileManager = FileManager.default
                                let filePath = pathComponent.path
                                if fileManager.fileExists(atPath: filePath) {
                                    activityIndicatior.stopAnimating()
                                    var documentInteractionController = UIDocumentInteractionController()
                                    documentInteractionController.url = destinationURL
                                    if !documentInteractionController.presentOpenInMenu(from: cell.bounds, in: view, animated: true) {
                                        print("You don't have an app installed that can handle ePub files.")

                                    }
                                }
                                else {
                                    Alert.showAlertView(on: self, message: "Unable to download file from remote server.")
                                }
                            }
                        }
                    }
                }
             }
        }
        else {
            Alert.showAlertView(on: self, message: "There is not enough available storage to download.")
        }
    }

我希望 ActivityIndicator 会一直动画直到 documentInteractionController 不出现。

您应该将所有下载文件的过程放在后台线程中。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // Some code here

    DispatchQueue.main.async {
        activityIndicatior.startAnimating()
    }

    DispatchQueue.global(qos: .userInitiated).async {  
        // Download file or perform expensive task

        DispatchQueue.main.async {
            activityIndicator.stopAnimating()
        }
    }
}

将您的代码拆分为具有单一职责的函数,这将使您的代码更易于调试。