0
我正在構建一個將其文件保存到用戶的iCloud Drive文件夾的應用程序。在我刪除iCloud Drive中的應用程序文件夾以查看會發生什麼之前,一切都一直很好。從那以後,每次打開應用程序,它都會嘗試將我的示例文件保存在iCloud中,但它不起作用(reloadiCloud()函數被設置爲在ViewWillAppear中運行)。有什麼我需要做的創建iCloud Drive文件夾?我的代碼如下。應用程序不重新創建iCloud Drive文件夾
func reloadiCloud() {
ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)
guard ubiquityURL != nil else {
print("Unable to access iCloud Account")
return
}
ubiquityURL = ubiquityURL?.appendingPathComponent("Documents")
metaDataQuery = NSMetadataQuery()
metaDataQuery?.predicate = NSPredicate(format: "NOT %K.pathExtension = ''", NSMetadataItemFSNameKey)
metaDataQuery?.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.metadataQueryDidFinishGathering), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: metaDataQuery!)
metaDataQuery!.start()
}
func metadataQueryDidFinishGathering(notification: NSNotification) -> Void {
let query: NSMetadataQuery = notification.object as! NSMetadataQuery
query.disableUpdates()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query)
query.stop()
if query.resultCount > 0 {
fileList = []
for var i in (0..<query.resultCount) {
let currentFileURL = query.value(ofAttribute: NSMetadataItemURLKey, forResultAt: i) as! URL
fileList.append(currentFileURL.lastPathComponent)
tableView.reloadData()
}
tableView.reloadData()
print(fileList)
} else {
let sampleFile = Bundle.main.url(forResource: "Sample", withExtension: "pdf")!
movetoiCloud(forURL: sampleFile)
}
}
func movetoiCloud(forURL: URL) {
let fileName = forURL.lastPathComponent
ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents/\(fileName)")
//Check if the filename exists and add "copy" to the new version
for var i in (0..<fileList.count) {
if fileList[i] == forURL.lastPathComponent {
let base = ubiquityURL?.absoluteURL.deletingLastPathComponent()
let endIndex = fileName.index(fileName.endIndex, offsetBy: -4)
let truncatedExtension = fileName.substring(from: endIndex)
let truncatedName = fileName.substring(to: endIndex).appending(" copy").appending(truncatedExtension)
ubiquityURL = base?.appendingPathComponent(truncatedName)
print("New ubiquity URL: \(ubiquityURL)")
}
}
do {
try filemgr.setUbiquitous(true, itemAt: forURL, destinationURL: (ubiquityURL)!)
reloadiCloud()
print("Move to iCloud OK")
} catch let error {
print("moveToiCloud failed: \(error.localizedDescription)")
}
}
Bumping the Bundle版本立即爲我工作。謝謝! – damote
樂意幫忙! @damote –
OMG,我在這裏搜索了2天。但是如果用戶以後從驅動器中刪除文件夾,它是否會重新創建文件夾? – ChanWarde