Create a directory and store files inside it in Swift

自古美人都是妖i 提交于 2019-12-22 10:47:29

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/32778691/create-a-directory-and-store-files-inside-it-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!