简体   繁体   中英

Create a directory and store files inside it in Swift

i am creating a directory so that i can save temp videos onto it as TempVideos is a folder now my video clips will be inside the folder...

func createTempDirectoryToStoreVideos(){
    var error: NSError?
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    tempVideoPath = documentsDirectory.stringByAppendingPathComponent("TempVideos")

    if (!NSFileManager.defaultManager().fileExistsAtPath(tempVideoPath!)) {

        NSFileManager.defaultManager() .createDirectoryAtPath(tempVideoPath!, withIntermediateDirectories: false, attributes: nil, error: &error)

    }

}

Now in these directory i want to store the videos as

   func saveCompressVideoToTempDirectory(var compressedVideoUrl:NSURL?){

    let data = NSData(contentsOfURL: compressedVideoUrl!)
    var error:NSError?
    var success = data?.writeToFile(tempVideoPath!, options: NSDataWritingOptions.AtomicWrite, error: &error)
    println(error)

    if let temp = success{

        if temp {

            println("success")

        }else{

            println("not valid ")

        }

    }

}

Howver i get error as

Optional(Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn't be completed. (Cocoa error 512.)" UserInfo=0x17407f6c0 {NSFilePath=/var/mobile/Containers/Data/Application/F1140A9F-8D16-444B-8679-9ED1AD3F5E6A/Documents/TempVideos, NSUnderlyingError=0x17424a320 "The operation couldn't be completed. Is a directory"})

Could you try createFileAtPath for that?

func createFileAtPath(_ path: String,
         contents data: NSData?,
       attributes attr: [String : AnyObject]?) -> Bool

The same thing concerns writeToFile :

func writeToFile(_ path: String,
     options writeOptionsMask: NSDataWritingOptions) throws

where, look out, path is

The location to which to write the receiver's bytes. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

You should write this:

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var dirpath: String = paths[0] as String
let filepath = dirpath.stringByAppendingPathComponent("myOwnData.mov")

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