Swift -- 将本地生成的UIImage进行持久化保存(存到文件中fileManager.createFile)
程序员文章站
2022-07-02 23:22:21
//在相册或者拍照的代理方法中struct ImageSource { var img: UIImage var title: String init(img: UIImage, title: String) { self.img = img self.title = title }} var familyImgsSource:[ImageSource] = [] { didSet{...
//项目所需要的数据结构
struct ImageSource {
var img: UIImage
var title: String
init(img: UIImage, title: String) {
self.img = img
self.title = title
}
}
//Set方法
var familyImgsSource:[ImageSource] = [] {
didSet{
collectionView.reloadData()
}
}
//相册或者拍照的代理方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var selectedImage:UIImage? = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
if (selectedImage == nil ) {
selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
if selectedImage != nil {
let sources = ImageSource.init(img: selectedImage!, title: "")
familyImgsSource.append(sources)
mySingleton.shareInstance.dataSourceImgsSingleton = familyImgsSource
//UserDefaut存储图片个数
UserDefaults.standard.set(mySingleton.shareInstance.dataSourceImgsSingleton.count, forKey: "imageCount")
UserDefaults.standard.synchronize()
//将选择的图片保存到Document目录下
let imageCount = UserDefaults.standard.integer(forKey: "imageCount")
var filePath = ""
for i in familyImgsSource {
//本文核心内容--图片的储存在Document目录下(文件形式)
let fileManager = FileManager.default
let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
for c in 0..<imageCount {
filePath = "\(rootPath)/pickedImage\(c).jpg"
}
let imageData = NSUIImageJPEGRepresentation(i.img, 1.0)
fileManager.createFile(atPath: filePath, contents: imageData, attributes: nil)
}
}
}
//在viewDidLoad初始化方法中获取存储的图片资源
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI(){
if UserDefaults.standard.integer(forKey: "imageCount") > 0 {
var newImageSource: [ImageSource] = []
let fileManager = FileManager.default
let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
for i in 0..<UserDefaults.standard.integer(forKey: "imageCount"){
//本文读取存储的图片核心内容
let filePath = "\(rootPath)/pickedImage\(i).jpg"
if fileManager.fileExists(atPath: filePath) {
if let imageData = fileManager.contents(atPath: filePath) {
//data转String
if let imageImage = UIImage.init(data: imageData) {
newImageSource.append(.init(img: imageImage, title: "张张"))
}
}
}
}
//赋值
familyImgsSource = newImageSource
}
}
本文地址:https://blog.csdn.net/SoftwareDoger/article/details/107538730