SWIFT - Загрузка файла в документы icloud не заканчивается - PullRequest
1 голос
/ 25 января 2020

Я использовал учебник на странице ниже, и по какой-то причине файл начинает загружаться и отображается на консоли на 95%, но никогда не показывает сообщение «резервная загрузка завершена». Приложение предназначено только для тестирования загрузки файла sample.mp4.

https://medium.com/swlh/backup-your-applications-data-with-icloud-and-track-progress-48a00ebd2891

//  BackupToIcloudController.swift


import Foundation

import UIKit

class BackupToIcloudController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: UIScreen.main.bounds.midX - 150, y: UIScreen.main.bounds.midY - 20, width: 300, height: 40))
        button.setTitle("Upload to iCloud", for: .normal)
        button.addTarget(self, action: #selector(self.uploadToCloud), for: .touchUpInside)
        button.backgroundColor = .blue
        view.addSubview(button)
    }

    @objc func uploadToCloud() {
        let backup = Backup.init()
        try? backup.startBackup()
    }

    @IBAction func back(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
}
//  Backup.swift


import Foundation

class Backup: NSObject {

   var query: NSMetadataQuery!

   override init() {
        super.init()
        initialiseQuery()
        addNotificationObservers()
    }
    func initialiseQuery() {

        query = NSMetadataQuery.init()
        query.operationQueue = .main
        query.searchScopes = [NSMetadataQueryUbiquitousDataScope]
        query.predicate = NSPredicate(format: "%K LIKE %@", NSMetadataItemFSNameKey, "sample.mp4")
    }

    func startBackup() throws {
        guard let fileURL = Bundle.main.url(forResource: "sample", withExtension: "mp4") else {
            return

        }
        guard let containerURL = FileManager.default.url(forUbiquityContainerIdentifier: "iCloud.mylojastore.com.backup") else { return }

        if !FileManager.default.fileExists(atPath: containerURL.path) {
            try FileManager.default.createDirectory(at: containerURL, withIntermediateDirectories: true, attributes: nil)
        }
        let backupFileURL = containerURL.appendingPathComponent("sample.mp4")
        if FileManager.default.fileExists(atPath: backupFileURL.path) {
           try FileManager.default.removeItem(at: backupFileURL)
            try FileManager.default.copyItem(at: fileURL, to: backupFileURL)
        } else {
            try FileManager.default.copyItem(at: fileURL, to: backupFileURL)
        }

        query.operationQueue?.addOperation({ [weak self] in
            _ = self?.query.start()
            self?.query.enableUpdates()
        })
    }
    func addNotificationObservers() {

        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSMetadataQueryDidStartGathering, object: query, queue: query.operationQueue) { (notification) in
            self.processCloudFiles()
        }

        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSMetadataQueryDidUpdate, object: query, queue: query.operationQueue) { (notification) in
            self.processCloudFiles()
        }
        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query, queue: query.operationQueue) { (notification) in
            self.processCloudFiles()
        }
        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSMetadataQueryGatheringProgress, object: query, queue: query.operationQueue) { (notification) in
                  print("progress")
               }
    }

    @objc func processCloudFiles() {

        if query.results.count == 0 { return }
        var fileItem: NSMetadataItem?
        var fileURL: URL?

        for item in query.results {

            guard let item = item as? NSMetadataItem else { continue }
            guard let fileItemURL = item.value(forAttribute: NSMetadataItemURLKey) as? URL else { continue }
            if fileItemURL.lastPathComponent.contains("sample.mp4") {
                fileItem = item
                fileURL = fileItemURL
            }
        }

        let fileValues = try? fileURL!.resourceValues(forKeys: [URLResourceKey.ubiquitousItemIsUploadingKey])
        if let fileUploaded = fileItem?.value(forAttribute: NSMetadataUbiquitousItemIsUploadedKey) as? Bool, fileUploaded == true, fileValues?.ubiquitousItemIsUploading == false {
            print("backup upload complete")

        } else if let error = fileValues?.ubiquitousItemUploadingError {
            print("upload error---", error.localizedDescription)

        } else {
            if let fileProgress = fileItem?.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? Double {
                print("uploaded percent ---", fileProgress)
            }
        }
    }
}
...