【问题标题】:How do I write a file in iOS using FileManager?如何使用 FileManager 在 iOS 中写入文件?
【发布时间】:2018-07-21 07:00:17
【问题描述】:

我有以下代码,其中语句旁边的 cmets 中的打印语句的结果:

    let myImageData = FileManager.default.contents(atPath: myURL.absoluteString)

    var mySaveToURL: URL = FileManager.default.url(forUbiquityContainerIdentifier: nil)!
    mySaveToURL.appendPathComponent(myURL.pathComponents.last!)

    print("mySaveToURL=", mySaveToURL) // mySaveToURL= file:///Users/shinehah/Library/Developer/CoreSimulator/Devices/693D4940-1B91-43E1-B5AD-88E9763046C7/data/Library/Mobile%20Documents/iCloud~us~gnolaum~TrialNotifications/ABF236AE-A6E7-403E-ADC4-5BAA5DC734B3.jpeg


    let resultCreateFile = FileManager.default.createFile(atPath: mySaveToURL.absoluteString, contents: myImageData, attributes: nil)

    print("resultCreateFile=", resultCreateFile) // resultCreateFile= false


    do {

        try FileManager.default.copyItem(at: myURL, to: mySaveToURL)

        print("copy success!") // copy success!

    } catch {

        print(error.localizedDescription)

    }

如您所见,我无法成功执行 FileManager 的 createFile() 方法,但能够成功地将 copyItem() 方法执行到同一 URL。

我要检查什么才能弄清楚如何让 createFile() 方法工作?

【问题讨论】:

    标签: ios swift nsfilemanager


    【解决方案1】:

    出现错误是因为您使用了错误的 API。要获取文件系统 URL 的路径,您必须使用 path

    let resultCreateFile = FileManager.default.createFile(atPath: mySaveToURL.path, contents: myImageData, attributes: nil)
    

    但是没有理由明确地创建文件。只需复制其他文件即可。

    【讨论】:

    • 好的。谢谢。我正在使用该代码来测试如何为 iOS 10 的向后兼容性编写代码,其中我从 UIImagePickerController 而不是 URL 获取 UIImage。再次感谢。
    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多