简体   繁体   中英

Persisting data in iOS documents directory

I have an app that saves a recorded video to the documents directory, as well as a Post object, and populates a collection view from the Post object. However upon restarting the app, the collection view is empty, so the videos being saved to the docs directory is not persisting (at least I think that's the problem).

This is the function that saves the video:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let mediaType = info[UIImagePickerControllerMediaType] as! NSString
    dismiss(animated: true, completion: nil)
    if mediaType == kUTTypeMovie {
        var uniqueVideoID = ""
        var videoURL:NSURL? = NSURL()
        var uniqueID = ""

        uniqueID = NSUUID().uuidString

        // Get the path as URL and store the data in myVideoVarData
        videoURL = info[UIImagePickerControllerMediaURL] as? URL as NSURL?
        let myVideoVarData = try! Data(contentsOf: videoURL! as URL)

        // Write data to temp diroctory
        let tempPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let tempDocumentsDirectory: AnyObject = tempPath[0] as AnyObject
        uniqueVideoID = uniqueID  + "TEMPVIDEO.MOV"
        let tempDataPath = tempDocumentsDirectory.appendingPathComponent(uniqueVideoID) as String
        try? myVideoVarData.write(to: URL(fileURLWithPath: tempDataPath), options: [])

        // Get the time value of the video
        let fileURL = URL(fileURLWithPath: tempDataPath)
        let asset = AVAsset(url: fileURL)
        let duration : CMTime = asset.duration

        // Remove the data from the temp Document Diroctory.
        do{
            let fileManager = FileManager.default
            try fileManager.removeItem(atPath: tempDataPath)
        } catch {
            //Do nothing
        }

        // Check to see if video is under the 18500 (:30 seconds)
        if duration.value <= 18500 {

            // Write the data to the Document Directory
            let docPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
            let documentsDirectory: AnyObject = docPaths[0] as AnyObject
            uniqueVideoID = uniqueID  + "VIDEO.MOV"
            let docDataPath = documentsDirectory.appendingPathComponent(uniqueVideoID) as String
            try? myVideoVarData.write(to: URL(fileURLWithPath: docDataPath), options: [])
            print("docDataPath under picker ",docDataPath)
            print("Video saved to documents directory")

            //Create a thumbnail image from the video
            let assetImageGenerate = AVAssetImageGenerator(asset: asset)
            assetImageGenerate.appliesPreferredTrackTransform = true
            let time = CMTimeMake(asset.duration.value / 3, asset.duration.timescale)
            if let videoImage = try? assetImageGenerate.copyCGImage(at: time, actualTime: nil) {
                //Add thumbnail & video path to Post object
                let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: UIImage(cgImage: videoImage))
                posts.append(video)
                print("Video saved to Post object")
            }
        }else{
            print("Video not saved")
        }
    }
}

Specifically, this is where the video path and thumbnail are added to my object:

            //Add thumbnail & video path to Post object
            if let videoImage = try? assetImageGenerate.copyCGImage(at: time, actualTime: nil) {
                let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: UIImage(cgImage: videoImage))
                posts.append(video)

So I do give it the path to the video in the documents directory; how can I ensure that the data persists there?

EDIT:

在此处输入图片说明

To verify if the videos are being saved on the device, connect the device to Xcode and navigate to Window->Devices in Xcode. Then select your device on the left and find your app in the Installed Apps list. Select your app and click on the gear icon at the bottom of the list and press 'Show Containter'. Wait for a few seconds and you should see all the folders in your app.

Secondly, not sure why you are writing the video and deleting it and writing it back again and also why use 'try?' instead of actually catching any exceptions thrown during the file write?

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