简体   繁体   中英

Having trouble saving a file in a folder inside Document directory in Swift 2

I am trying to save a file inside a subfolder in Documents directory but it won't save. I can't seem to find what's wrong. Here is what I've tried:

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)
        }

    }

Here is where I want to save the file:

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

But it keeps on giving me "error saving file".

First of all, use always writeToURL:options:error to get a (more) descriptive error message.

The issue is quite simple: You forgot to provide a file name.

Technically you're going to overwrite an existing folder with data. That's not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM