【问题标题】:How to save pdf document to iCloud Drive programmatically using swift?如何使用 swift 以编程方式将 pdf 文档保存到 iCloud Drive?
【发布时间】:2018-02-04 22:45:19
【问题描述】:

我的应用程序创建了一个 pdf 文件,我想使用 swift 3 以编程方式将该 pdf 文档保存到 iCloud Drive

作为示例,这里我使用文本文件保存在 iCloud Drive 中。

这是我的代码:

func copyDocumentsToiCloudDrive() {
    var error: NSError?
    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("myCloudTest")

    do{
        //is iCloud working?
        if  iCloudDocumentsURL != nil {
            //Create the Directory if it doesn't exist
            if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: nil)) {
                //This gets skipped after initial run saying directory exists, but still don't see it on iCloud
                try FileManager.default.createDirectory(at: iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
            }
        } else {
            print("iCloud is NOT working!")
            //  return
        }

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

        //Set up directorys
        let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL

        //Add txt file to my local folder
        let myTextString = NSString(string: "HELLO WORLD")
        let myLocalFile = localDocumentsURL.appendingPathComponent("myTextFile.txt")
        _ = try myTextString.write(to: myLocalFile!, atomically: true, encoding: String.Encoding.utf8.rawValue)

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

        //If file exists on iCloud remove it
        var isDir:ObjCBool = false
        if (FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: &isDir)) {
            try FileManager.default.removeItem(at: iCloudDocumentsURL!)
        }

        //copy from my local to iCloud
        if error == nil {
            try FileManager.default.copyItem(at: localDocumentsURL as URL, to: iCloudDocumentsURL!)
        }
    }
    catch{
        print("Error creating a file")
    }

}

此代码运行正常,没有任何错误。但未在 iCloud Drive 中显示保存的文件。

我参考了这个link,我写了这段代码。

【问题讨论】:

  • 得到了输出.. !!我有同样的问题。正在创建文件夹,但里面缺少文件。你能指导我吗?
  • 我有同样的问题,你有解决这个问题的办法吗?如果是,那么你能分享一下吗
  • 尚无解决方案。 :(

标签: ios swift swift3 cloudkit icloud-drive


【解决方案1】:

假设您的代码按预期工作,请尝试在 info.plist 中更新您的应用程序的版本和内部版本号。需要更改这些值才能反映 iCloud 更改。

【讨论】:

  • 就我而言,它仅在更新内部版本号后才起作用。
猜你喜欢
  • 2017-10-11
  • 1970-01-01
  • 2016-02-03
  • 2018-02-01
  • 2018-01-17
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
相关资源
最近更新 更多