How to save a UIImage to documents directory?

前端 未结 1 542
眼角桃花
眼角桃花 2021-01-12 04:50

I\'m trying to save both a recorded video\'s file path, and a thumbnail from the video to the documents directory. Then, set those two values to an object using the file pat

相关标签:
1条回答
  • 2021-01-12 05:44

    One Suggestion: Save images to Library/Caches if that can be downloaded again as per apple's guide line.


    As simple as this:

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

    Swift4:

    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 dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyyMMddhhmmss"
    
            let filename = dateFormatter.string(from: Date()).appending(".jpg")
            let filepath = directoryPath.appending(filename)
            let url = NSURL.fileURL(withPath: filepath)
            do {
                try chosenImage.jpegData(compressionQuality: 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
            }
        }
    
    0 讨论(0)
提交回复
热议问题