ios – 如何将UIImage保存到文档目录?

我正在尝试将录制视频的文件路径和缩略图从视频保存到文档目录.然后,使用文件路径将这两个值设置为对象,以便我可以使用该对象填充集合视图.使用我目前(下面)的代码,在录制视频后,视频路径被保存到文档目录,视频路径和缩略图被设置为我的Post对象,缩略图在我的集合视图中正确显示.到目前为止都很好.

但是,只有视频路径在应用程序重新启动之间持续存在,因为它位于目录中,而缩略图则不然.我也想在那里保存缩略图,但我不知道如何去做,因为它似乎只能写入目录的URL.

这是我第一次使用文档目录,所以任何帮助将不胜感激!如何将缩略图(UIImage)与其来自的视频一起写入我的文档目录?

到目前为止,这是我的代码

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

    let mediaType = info[UIImagePickerControllerMediaType] as! NSString
    dismiss(animated: true,completion: nil)

    if mediaType == kUTTypeMovie {
        // Componenets for a unique ID for the video
        var uniqueVideoID = ""
        var videoURL:NSURL? = NSURL()
        var uniqueID = ""
        uniqueID = NSUUID().uuidString

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

        // Write the video to the Document Directory at myVideoVarData (and set the video's unique ID)
        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 (first frame)
        let asset = AVAsset(url: URL(fileURLWithPath: docDataPath))
        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")
        }
    }
}

解决方法

就这么简单:
func saveImageToDocumentDirectory(_ chosenImage: UIImage) -> String {
        let directoryPath =  NSHomeDirectory().appending("/Documents/")
        if !FileManager.default.fileExists(atPath: directoryPath) {
            do {
                try FileManager.default.createDirectory(at: NSURL.fileURL(withPath: directoryPath),withIntermediateDirectories: true,attributes: nil)
            } catch {
                print(error)
            }
        }
        let filename = NSDate().string(withDateFormatter: yyyytoss).appending(".jpg")
        let filepath = directoryPath.appending(filename)
        let url = NSURL.fileURL(withPath: filepath)
        do {
            try UIImageJPEGRepresentation(chosenImage,1.0)?.write(to: url,options: .atomic)
            return String.init("/Documents/\(filename)")

        } catch {
            print(error)
            print("file cant not be save at path \(filepath),with error : \(error)");
            return filepath
        }
    }

一个建议:如果可以按照苹果的指南再次下载图像,则将图像保存到库/缓存中.

相关文章

背景 前端时间产品经理决定使用百度统计,使得 工程B 中原统计sdk-友盟统计,需要被去除。之前尝试去除...
结论: alloc负责分配内存和创建对象对应的isa指针; init只是返回alloc生成的对象。 所以alloc后,多次...
更新 如果UI愿意把启动图切割成n份,按一定约束在launchscreen.storyboard中进行排版,启动图效果会更好...
最近在看一本书《Effective OC 2.0》,今天看到有个tip是OC适中循环各自优劣性,作者最终推荐此块循环。...
// // ViewController.m // paintCodeTestOC //gif // Created by LongMa on 2019/7/25. // #import &a...
背景介绍 一般情况下,出于省电、权限、合理性等因素考虑,给人的感觉是很多奇怪的需求安卓可以实现,但...