首页 文章

如何使用FileManager在iOS中编写文件?

提问于
浏览
0

我在语句旁边的注释中有以下代码和print语句的结果:

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()方法工作?

1 回答

  • 1

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

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

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

相关问题