Swift FileManager - 没有这样的文件

时间:2018-03-07 11:09:19

标签: swift url swift3 nsfilemanager

我正在尝试上传视频。我对fileExists也是如此,但在日志中我看到了 -

  

正文文件无法访问:   /private/var/mobile/Containers/Data/Application/BE71B534-5051-4552-8491-30E1FE34E128/Documents/upload/306A4291-5E5A-467E-B2F7-8FFCA5BFFC1D1520419887-676644831.mp4

     

错误域= NSCocoaErrorDomain代码= 260"文件   “306A4291-5E5A-467E-B2F7-8FFCA5BFFC1D1520419887-676644831.mp4”   因为没有这样的文件而无法打开。"

let dir = "/upload/"
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let path = documentsUrl.appendingPathComponent(dir)

    do {

        if let urlArray = try? FileManager.default.contentsOfDirectory(at: path,
                                                                       includingPropertiesForKeys: [.contentModificationDateKey],
                                                                       options:.skipsHiddenFiles)  {

            let mp4Files = urlArray.filter{ $0.pathExtension == "mp4" }

            for videoFile in urlArray {

                let fileExists = FileManager().fileExists(atPath: videoFile.path)

                if fileExists {


                    let url = URL.init(fileURLWithPath: videoFile.path)

                    self.uploadVideo(url: url)
                }


            }
        }

    } catch {
        print(error.localizedDescription)
    }

要保存我使用的视频 -

        let urlData = NSData(contentsOf: videoUrl)

        if((urlData) != nil) {

            DispatchQueue.main.async(execute: { () -> Void in

                urlData?.write(toFile: path, atomically: true)

            })
        }

2 个答案:

答案 0 :(得分:0)

试试这个,

使用此代码创建目录

var nextItemDirUrl : URL!

func createDownloadSongDirIfNotForNextItem() {
        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let logsPath = documentsDirectoryURL.appendingPathComponent("upload")
        nextItemDirUrl = logsPath

        do {
            try FileManager.default.createDirectory(atPath: logsPath.path, withIntermediateDirectories: true, attributes: nil)
            print("Directory created at:",logsPath)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
    }

使用nextItemDirUrl

中的DocumentDirectory保存文件后
let destinationUrl = nextItemDirUrl.appendingPathComponent("yourView.mp4")
yourVideoData.write(to: destinationUrl, atomically: true)

答案 1 :(得分:0)

我设法通过做 -

来解决这个问题
let urlData = NSData(contentsOf: videoFile)

    if((urlData) != nil) {

       let lastPath = "/videos/" + "temp.mp4"

       let path = documentDirectory.appending(lastPath)

       urlData?.write(toFile: path, atomically: true)
       let fileURL = URL.init(fileURLWithPath: path)
       self.uploadVideo(url: url)
}