美文网首页
保存照片swiftUI

保存照片swiftUI

作者: 王勋才 | 来源:发表于2021-10-07 21:45 被阅读0次
    //
    //  LocalFileManager.swift
    //  SwiftUIByExample
    //
    //  Created by wangxuncai on 2021/10/7.
    //
    
    import Foundation
    import SwiftUI
    
    class LocalFileManager{
        static let instance = LocalFileManager()
        private init(){}
        
        //保存照片
        func saveImage(image:UIImage,imageName:String,foldName:String){
            creatFolderIfNeeded(folderName: foldName)
            guard
                let data = image.pngData(),
                let url = getImageUrl(imageName: imageName, foldName: foldName)
            else{return}
            do {
                try data.write(to: url)
            } catch let error {
                print("save image failed . \(error)")
            }
        }
        //获取照片
        func getImage(imageName:String,folderName:String)->UIImage?{
            guard
                let url = getImageUrl(imageName: imageName, foldName: folderName),
                FileManager.default.fileExists(atPath: url.path) else {
                    return nil
                }
            return UIImage(contentsOfFile: url.path)
        }
        
        //create folder
        private func creatFolderIfNeeded(folderName:String){
            guard let url = getFoldUrl(foldName: folderName) else {return}
            if !FileManager.default.fileExists(atPath: url.path){
                do {
                    try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
                } catch let error {
                    print("creat Folder  failed .\(error)")
                }
            }
        }
        //get url
     private   func getFoldUrl(foldName:String)->URL?{
            guard   let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else{
                return nil
            }
            return url.appendingPathComponent(foldName)
        }
      //get image url
        private func getImageUrl(imageName:String,foldName:String)->URL?{
            guard let url = getFoldUrl(foldName: foldName) else{return nil}
            return url.appendingPathComponent(imageName).appendingPathExtension(".png")
        }
    }
    
    苹果应用商店搜 王勋才 有我全部作品
    

    相关文章

      网友评论

          本文标题:保存照片swiftUI

          本文链接:https://www.haomeiwen.com/subject/dlttoltx.html