2
votes

I am building an app which saves its files to the user's iCloud Drive folder. Everything has been working great until I deleted the app's folder in iCloud Drive to see what would happen. Since then, every time I open the app, it tries to save my sample file in iCloud but it doesn't work (the reloadiCloud() function is set to run in ViewWillAppear). Is there something else I need to do to create the iCloud Drive folder? My code is below.

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)")
    }
}
1

1 Answers

3
votes

Try updating the bundle number and version in the info plist, an increase in these values are needed for the icloud additions to take effect.