【问题标题】:Having trouble saving a file in a folder inside Document directory in Swift 2在 Swift 2 的 Document 目录中的文件夹中保存文件时遇到问题
【发布时间】:2016-09-04 22:59:43
【问题描述】:

我正在尝试将文件保存在 Documents 目录的子文件夹中,但它不会保存。我似乎无法找到问题所在。这是我尝试过的:

if let audioUrl = NSURL(string: "http://pillar.foundationu.com/wp-content/plugins/pillar-data-sync/php/htmlBreakdownResult.json") {

        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!

        do {
            let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
            print(directoryContents[0].path!)

            if NSFileManager().fileExistsAtPath(String(audioUrl.path!)) {
                                print("The file already exists at path")

            } else {
                                //  if the file doesn't exist
                                //  just download the data from your url
                    if let myAudioDataFromUrl = NSData(contentsOfURL: audioUrl){
                                    // after downloading your data you need to save it to your destination url
                    if myAudioDataFromUrl.writeToURL(NSURL(fileURLWithPath: directoryContents[0].path!), atomically: true) {
                                print("file saved")

                    } else {
                                print("error saving file")
                            }

                        }
                    }



        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }

这是我要保存文件的位置:

/Users/rendell/Library/Developer/CoreSimulator/Devices/5A052CC5-FD34-44FD-B060-24D6F1970860/data/Containers/Data/Application/37753B0B-FAB0-478D-A7F8-98E3039D07DD/Documents/MyFolder2

但它一直给我“错误保存文件”。

【问题讨论】:

    标签: ios swift swift2 nsfilemanager


    【解决方案1】:

    首先,始终使用writeToURL:options:error 来获取(更多)描述性错误消息。

    问题很简单:您忘记提供文件名。

    从技术上讲,您将用数据覆盖现有文件夹。这是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-21
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2013-07-28
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多