swift 如何检查上传到iCloud的项目的进度

rvpgvaaj  于 2023-10-15  发布在  Swift
关注(0)|答案(1)|浏览(133)

我已经实现了备份系统,就像我们在WhatsApp中一样。
1.首先,它检查文档目录并将数据压缩到临时目录。
1.然后获取iCloud的URL

func getUrlToiCloud() -> URL? {
let fileManager = FileManager.default
let url = fileManager.url(forUbiquityContainerIdentifier: nil)
return url
}

1.接下来是将项目备份到iCloud

func iCloudBackupHandler(_ backupName: String, backupPath: String) {
guard let url = getUrlToiCloud()  else {
    return
}

let loggedInUser: String
if #available(iOS 10.0, *) {
    loggedInUser = CKCurrentUserDefaultName
} else {
    loggedInUser = CKOwnerDefaultName
}
print("loggedInUser:\(loggedInUser)")
let localBackupUrl = URL(fileURLWithPath: backupPath)
let iCloudDocumentUrl = url.appendingPathComponent(backupName)
print("Local:\(localBackupUrl)")
print("iCloudDocumentUrl:\(String(describing: iCloudDocumentUrl))")
do {
    try FileManager.default.replaceItem(at: iCloudDocumentUrl, withItemAt: localBackupUrl, backupItemName: backupName, options: .withoutDeletingBackupItem, resultingItemURL: nil)
   //try FileManager.default.setUbiquitous(true, itemAt: localBackupUrl, destinationURL: iCloudDocumentUrl)
} catch {
    print("error while backup: \(error)")
}
}

我的问题在这里,在下面的一行。将项目备份到iCloud。

try FileManager.default.replaceItem(at: iCloudDocumentUrl, withItemAt: localBackupUrl, backupItemName: backupName, options: .withoutDeletingBackupItem, resultingItemURL: nil)

如何跟踪文件上传到iCloud的进度?与WhatsApp一样,备份文件的进度(百分比)。请让我知道,如果你有这个想法。

fdx2calv

fdx2calv1#

假设你已经有fileUrl了。

do {
                   
            let fileValues = try fileURL?.resourceValues(forKeys: [URLResourceKey.ubiquitousItemIsUploadingKey])
//Please add more checks for error, success too
if fileValues?.ubiquitousItemIsUploading == true {
   if let fileProgress = fileItem?.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? Double {
        print("uploaded percent ---", fileProgress)
     }
  } 
} catch {
    print(error.localizedDescription)
    NotificationCenter.default.post(name: NSNotification.Name("backupError"), object: nil, userInfo: nil)
}

相关问题