Xcode Swift,将CSV导出到iCloud文档也可以保存核心数据模型

时间:2019-03-20 20:47:03

标签: core-data nsfilemanager swift4.2 icloud-documents

我有一个函数可以将我的Core Data模型解析为CSV文件,然后将其保存到用户本地目录,然后移至其iCloud Documents目录。出于某种原因,每次单击“保存”时,我也会同时在目录中获得Core Data模型的副本。 “我的执行/捕获”不包含任何直接引用我的模型的内容-我只是通过数组进行解析并创建CSV:

func exportDataToCloud() {
    let error : Error? = nil
    let fileName = "exportedFile.csv"
    var csvText = "COL1,COL2,COL3,COL4,COL5,COL6\n"

    // Define local and iCloud directories
    let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL
    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")

    do {
        if  iCloudDocumentsURL != nil {
            // Create the Directory if it doesn't exist
            if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: nil)) {
                print("Creating iCloud directory")
                try FileManager.default.createDirectory(at: iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
            } else {
                print("iCloud directory already exists")
            }
        } else {
            // display alert
            print("iCloud is NOT working!")
        }

        if error != nil {
            print("Error creating iCloud DIR")
        }

        // Add txt file to my local folder
        print("creating local file")
        let myLocalFile = localDocumentsURL.appendingPathComponent(fileName)
        _ = try csvText.write(to: myLocalFile!, atomically: true, encoding: String.Encoding.utf8)

        if ((error) != nil){
            print("Error saving to local DIR")
        }

        // If file exists on iCloud remove it
        print("Does the file already exist in iCloud?")
        var isDir:ObjCBool = false
        if (FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: &isDir)) {
            print("Deleting the old file")
            try FileManager.default.removeItem(at: iCloudDocumentsURL!)
        }

        // Copy file from my local directory to iCloud
        if error == nil {
            print("Copy new file from my local directory to iCloud directory")

            try FileManager.default.copyItem(at: localDocumentsURL as URL, to: iCloudDocumentsURL!)
        }
    }
    catch {
        print("Error creating a file")
    }
}

...但是每次我导出CSV文件时,Core Data模型标签也会随之出现。

如果我正确阅读了Apple的文档,则可能与未指定实际文件有关,因此默认情况下它将复制目录中的所有内容。如果确实如此,那么如何指定仅移动特定文件?我正在将初始文件作为fileName写入本地目录,但是随后我想将其向上移动到用户iCloud Documents目录,以使其不再位于本地目录中。我在本地目录中唯一需要的就是Core Data存储。

0 个答案:

没有答案