Commit c41d849d authored by CZ1004's avatar CZ1004

首页优化

parent 321e2eec
......@@ -7,6 +7,7 @@
import UIKit
import AppIntents
import Photos
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
......@@ -30,9 +31,269 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
let battery = WidgetPublicModel.battery()
let storage = WidgetPublicModel.UseDiskSpace() * 100
widgetAppgourp.share.PushWidgetData(battery: Int(battery), storage: Int(storage))
findHomeData()
return true
}
func findHomeData(){
PhotoAndVideoMananger.getPrivacy {[weak self] status in
guard let self else {return}
if let photoStatus = status as? PrivacyType {
switch photoStatus {
case .authorized:
PhotoAndVideoMananger.mananger.setAssets()
readCacheModel()
break
case .denied:
Print("未获取授权")
break
case .restricted:
Print("未获取授权")
break
case .notDetermined:
Print("未获取授权")
break
}
}
}
}
var dataArrayDu : [[AssetModel]] = []
var dataArraySi : [[AssetModel]] = []
var dataArraySc : [[AssetModel]] = []
var dataDuFileSize : Double = 0.0
var dataSiFileSize : Double = 0.0
var dataScFileSize : Double = 0.0
func readCacheModel(){
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let url = paths[0].appendingPathComponent("photosManagerData.json")
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let model = try decoder.decode(PhotosManagerModel.self, from: data)
self.dataArrayDu = model.titleModelArray[0].assets
self.dataArraySi = model.titleModelArray[1].assets
self.dataArraySc = model.otherModelArray[1].assets
self.dataDuFileSize = model.titleModelArray[0].allFileSize
self.dataSiFileSize = model.titleModelArray[1].allFileSize
self.dataScFileSize = model.otherModelArray[1].allFileSize
// 更新视频数据
Print("更新视频数据")
let videoCount = model.otherModelArray[0].assets.count
// 查看是否有更新
if videoCount != PhotoAndVideoMananger.mananger.videoAssets.count {
// 先移除数据
model.otherModelArray[0].assets.removeAll()
model.otherModelArray[0].allFileSize = 0
// 重新更新下
PhotoAndVideoMananger.mananger.dealVideoData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model.otherModelArray[0].assets = data
model.otherModelArray[0].allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
// 发起通知,更新UI
let dataUpdated = Notification.Name("HomeVideoResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
Print("更新视频数据结束")
})
}
Print("更新相似视频数据")
PhotoAndVideoMananger.mananger.fetXSVideo { array in
PhotoSimilarityFinder.processSimilarVideoGroups(videoGroups: array) {ids in
var dataArray : [AssetModel] = []
for item in ids {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model.otherModelArray[3].assets = ids
model.otherModelArray[3].allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeSimilarVideoResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
Print("更新相似视频结束")
}
}
}
Print("更新截图数据")
let screeshotCount = model.otherModelArray[2].assets.count
if screeshotCount != PhotoAndVideoMananger.mananger.screenShotAssets.count {
// 先移除数据
model.otherModelArray[2].assets.removeAll()
model.otherModelArray[2].allFileSize = 0
PhotoAndVideoMananger.mananger.dealScreenShotData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model.otherModelArray[2].assets = data
model.otherModelArray[2].allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeScreenShotResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
Print("更新截图数据结束")
})
}
}
Print("更新照片数据")
let imageCount = model.otherModelArray[4].assets.count
if imageCount != PhotoAndVideoMananger.mananger.otherAssets.count{
PhotoAndVideoMananger.mananger.dealImageAssetData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model.otherModelArray[4].assets = data
model.otherModelArray[4].allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeOtherResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
Print("更新照片数据结束")
})
}
}
// 更新重复图片和截图
// 查看更新到了哪一个时间点了【这里以时间为基准】
var allImageUpdateLocation = UserDefaults.standard.object(forKey: "allImageUpdateLocationDate")
if allImageUpdateLocation == nil {
allImageUpdateLocation = []
}
// 找到位置
var newArray : [PHAsset] = []
for item in PhotoAndVideoMananger.mananger.allAssets {
if !(allImageUpdateLocation as! [String]).contains(item.localIdentifier) {
newArray.append(item)
}
}
if newArray.count > 0 {
// 继续比较
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: newArray, type: 0, threshold: 0.99) { data1,data2 in
var dataArray1 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
}
var dataArray2 : [AssetModel] = []
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: {[dataArray1 = dataArray1] fileSize,index in
if dataArray1.count > 0 {
self.dataArrayDu.append(dataArray1)
model.titleModelArray[0].assets = self.dataArrayDu
self.dataArrayDu.remove(at: self.dataArrayDu.count - 1)
model.titleModelArray[0].allFileSize = self.dataDuFileSize + Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeDupImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
}
})
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray2)!,progress: { fileSize, index in
// 不做处理
}, completion: {[model = model]fileSize,index in
if dataArray2.count > 0 {
self.dataArraySi.append(dataArray2)
model.titleModelArray[0].assets = self.dataArraySi
self.dataArraySi.remove(at: self.dataArraySi.count - 1)
model.titleModelArray[1].allFileSize = self.dataSiFileSize + Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeSimilarImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
}
})
} completionHandler: { data1, data2 in
}
}
// 处理相似截图
var screenshotUpdateLocation = UserDefaults.standard.object(forKey: "screenshotUpdateLocationDate")
if screenshotUpdateLocation == nil {
screenshotUpdateLocation = []
}
// 找到位置
var screenshotNewArray : [PHAsset] = []
for item in PhotoAndVideoMananger.mananger.screenShotAssets {
if !(screenshotUpdateLocation as! [String]).contains(item.localIdentifier) {
screenshotNewArray.append(item)
}
}
if screenshotNewArray.count > 0 {
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: screenshotNewArray, type: 1, threshold: 0.99) { data1,data2 in
var dataArray2 : [AssetModel] = []
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray2)!,progress: { fileSiez, index in
// 不做处理
}, completion: {[model = model] fileSize,index in
if dataArray2.count > 0 {
self.dataArraySc.append(dataArray2)
model.titleModelArray[0].assets = self.dataArraySc
self.dataArraySc.remove(at: self.dataArraySc.count - 1)
model.otherModelArray[1].allFileSize = self.dataScFileSize + Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: model)
let dataUpdated = Notification.Name("HomeSimilarScreenshotResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
}
})
} completionHandler: { data1, data2 in
}
}
}catch{
Print("获取首页数据失败")
PhotoDataManager.manager.loadDataFromPhotos { model in}
}
}
private func setupDefault() {
......@@ -48,7 +309,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
PhotoAndVideoMananger.mananger.setAssets()
}
}
}
......
......@@ -305,6 +305,8 @@ class CompressCompletedViewController : BaseViewController{
}){ success, error in
if(success){
self.updateCompressData(flag: data.ident)
var deleteModel = AssetModel(localIdentifier: data.ident, assetSize: data.orgSize, createDate: data.createDate)
PhotoDataManager.manager.removeDataWhenDeleteInPage(data: [deleteModel])
print("删除文件成功")
}else {
if let error = error {
......
......@@ -67,6 +67,10 @@ class HomeInfoViewController:BaseViewController {
}
}
}
// 删除缓存数据
PhotoDataManager.manager.removeDataWhenDeleteInPage(data: array as! [AssetModel])
if HomePayModel.share.isNoAd == false {
if self.type == .duplicates { // 重复
HomePayViewController.show {
......
......@@ -357,8 +357,10 @@ extension HomePhotosDetailViewController:WaterfallMutiSectionDelegate,UICollecti
print("删除文件成功")
// 移除当前总数据源的数据
for item in self.selectedModel {
// 移除当前数据
self.resourceData.removeAll{ $0.localIdentifier == item.localIdentifier }
}
PhotoDataManager.manager.removeDataWhenDeleteInPage(data: self.selectedModel)
}else {
if let error = error {
print("删除文件时出错: \(error.localizedDescription)")
......
......@@ -332,6 +332,7 @@ extension HomeVideoDetailController:WaterfallMutiSectionDelegate,UICollectionVie
for item in self.selectedModel {
self.resourceData.removeAll{ $0.localIdentifier == item.localIdentifier }
}
PhotoDataManager.manager.removeDataWhenDeleteInPage(data: self.selectedModel)
}else {
if let error = error {
print("删除文件时出错: \(error.localizedDescription)")
......
......@@ -18,9 +18,40 @@ class HomeViewController:BaseViewController {
super.viewDidLoad()
let dataUpdated = Notification.Name("DataUpdatedNotification")
NotificationCenter.default.addObserver(self, selector: #selector(handleDataUpdated(_:)), name: dataUpdated, object: nil)
// 视频
let homeVideoResourceUpdate = Notification.Name("HomeVideoResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeVideoResourceUpdate(_:)), name: homeVideoResourceUpdate, object: nil)
// 相似视频
let homeSimilarVideoResourceUpdate = Notification.Name("HomeSimilarVideoResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeSimilarVideoResourceUpdate(_:)), name: homeSimilarVideoResourceUpdate, object: nil)
// 相似截图
let homeSimilarScreenshotResourceUpdate = Notification.Name("HomeSimilarScreenshotResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeSimilarScreenshotResourceUpdate(_:)), name: homeSimilarScreenshotResourceUpdate, object: nil)
// 屏幕截图
let homeScreenShotResourceUpdate = Notification.Name("HomeScreenShotResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeScreenShotResourceUpdate(_:)), name: homeScreenShotResourceUpdate, object: nil)
// 其他
let homeOtherResourceUpdate = Notification.Name("HomeOtherResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeOtherResourceUpdate(_:)), name: homeOtherResourceUpdate, object: nil)
// 重复图片
let homeDupImageResourceUpdate = Notification.Name("HomeDupImageResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeDupImageResourceUpdate(_:)), name: homeDupImageResourceUpdate, object: nil)
// 相似图片
let homeSimilarImageResourceUpdate = Notification.Name("HomeSimilarImageResourceUpdate")
NotificationCenter.default.addObserver(self, selector: #selector(handleHomeSimilarImageResourceUpdate(_:)), name: homeSimilarImageResourceUpdate, object: nil)
view.backgroundColor = .green
homeView = HomeView(frame: view.bounds)
......@@ -120,12 +151,16 @@ class HomeViewController:BaseViewController {
}
func setupData() {
// 详情数据
PhotoDataManager.manager.loadFromFileSystem(resultModel: {[weak self] model in
self?.homeView?.model = model
DispatchQueue.main.async {
self?.homeView?.model = model
self?.homeView?.collectionView.reloadData()
}
})
......@@ -149,6 +184,18 @@ class HomeViewController:BaseViewController {
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 可能是删除数据,重新获取下
PhotoDataManager.manager.loadFromFileSystem(resultModel: {[weak self] model in
DispatchQueue.main.async {
self?.homeView?.model = model
self?.homeView?.collectionView.reloadData()
}
})
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
......@@ -183,8 +230,126 @@ class HomeViewController:BaseViewController {
}
}
// 重复图片
@objc func handleHomeDupImageResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.titleModelArray[0].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if self.homeView?.dupHeadCell != nil && count == 0 && model.titleModelArray[0].assets.count != 0 {
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 0, section: 0)])
}
let tempCell = self.homeView?.collectionView.cellForItem(at: IndexPath(row: 0, section: 0))
if let homeTitleCell = tempCell as? HomeTitleCollectionCell {
var tempCount : Int = 0
for item in model.titleModelArray[0].assets {
tempCount = tempCount + item.count
}
homeTitleCell.fileLabel?.text = "\(tempCount)" + " Photos " + (model.titleModelArray[0].allFileSize > 0 ? "(\(formatFileSize(model.titleModelArray[0].allFileSize)))" : "(Calculating...)")
}
}
}
}
@objc func handleHomeSimilarImageResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.titleModelArray[1].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if self.homeView?.similarHeadCell != nil && count == 0 && model.titleModelArray[1].assets.count != 0 {
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 1, section: 0)])
}
let tempCell = self.homeView?.collectionView.cellForItem(at: IndexPath(row: 1, section: 0))
if let homeTitleCell = tempCell as? HomeTitleCollectionCell {
var tempCount : Int = 0
for item in model.titleModelArray[1].assets {
tempCount = tempCount + item.count
}
homeTitleCell.fileLabel?.text = "\(tempCount)" + " Photos " + (model.titleModelArray[1].allFileSize > 0 ? "(\(formatFileSize(model.titleModelArray[1].allFileSize)))" : "(Calculating...)")
}
}
}
}
@objc func handleHomeVideoResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.otherModelArray[0].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if count == 0{
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 0, section: 1)])
}
}
}
}
@objc func handleHomeSimilarScreenshotResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.otherModelArray[1].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if count == 0 && model.otherModelArray[1].assets.count != 0{
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 1, section: 1)])
}
let tempCell = self.homeView?.collectionView.cellForItem(at: IndexPath(row: 1, section: 1))
if let otherCell = tempCell as? HomeOtherCollectionCell{
var tempCount : Int = 0
for item in model.otherModelArray[1].assets {
tempCount = tempCount + item.count
}
otherCell.countLabel.text = "\(tempCount) Photos"
}
}
}
}
@objc func handleHomeScreenShotResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.otherModelArray[2].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if count == 0{
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 2, section: 1)])
}
}
}
}
@objc func handleHomeSimilarVideoResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.otherModelArray[3].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if count == 0{
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 3, section: 1)])
}
}
}
}
@objc func handleHomeOtherResourceUpdate(_ notification: Notification) {
PhotoDataManager.manager.loadFromFileSystem {[weak self] model in
guard let self else {return}
let count = self.homeView?.model?.otherModelArray[4].assets.count
self.homeView?.model = model
DispatchQueue.main.async {
if count == 0{
self.homeView?.collectionView.reloadItems(at: [IndexPath(row: 4, section: 1)])
}
}
}
}
@objc func handleDataUpdated(_ notification: Notification) {
......
......@@ -16,6 +16,10 @@ class HomeView:UIView {
private var bottomView:UIView?
var dupHeadCell : HomeTitleCollectionCell?
var similarHeadCell : HomeTitleCollectionCell?
var titleCallBack:(HomePhotosModel,PhotsFileType)->Void = {model,type in}
var indexCallBack:callBack<Any> = {index in }
......@@ -32,7 +36,7 @@ class HomeView:UIView {
guard let self else {return}
self.collectionView.reloadData()
// self.collectionView.reloadData()
}
}
}
......@@ -235,6 +239,11 @@ extension HomeView:WaterfallMutiSectionDelegate,UICollectionViewDataSource,UICol
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeTitleCollectionCell.identifiers, for: indexPath) as! HomeTitleCollectionCell
cell.model = model?.titleModelArray[indexPath.row]
if indexPath.row == 0 {
self.dupHeadCell = cell
}else{
self.similarHeadCell = cell
}
return cell
case 1:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeOtherCollectionCell.identifier, for: indexPath) as! HomeOtherCollectionCell
......
......@@ -27,35 +27,101 @@ class PhotoDataManager {
do {
let data = try encoder.encode(model)
try data.write(to: url)
print("数据保存成功: \(url.path)")
} catch {
print("保存失败: \(error.localizedDescription)")
}
}
func removeDataWhenDeleteInPage(data:[AssetModel]){
PhotoDataManager.manager.loadFromFileSystem(resultModel: {[weak self] model in
// 删除视频和图片和截图缓存
for index in 0..<model.otherModelArray.count {
if index == 0 || index == 2 || index == 4 {
var array = model.otherModelArray[index].assets.first
for item in data {
array = array?.filter { $0.localIdentifier != item.localIdentifier }
}
var finalyVideoData : [[AssetModel]] = []
finalyVideoData.append(array!)
model.otherModelArray[index].assets = finalyVideoData
}else{
// 删除相似截图和相似视频的缓存
var finalyVideoData : [[AssetModel]] = []
var array = model.otherModelArray[index].assets
for item in data {
for modelData in array {
var tempArray = modelData
tempArray = tempArray.filter { $0.localIdentifier != item.localIdentifier }
if tempArray.count >= 2 {
finalyVideoData.append(tempArray)
}
}
}
model.otherModelArray[index].assets = finalyVideoData
}
}
for index in 0..<model.titleModelArray.count {
// 删除相似截图和相似视频的缓存
var finalyVideoData : [[AssetModel]] = []
var array = model.titleModelArray[index].assets
for item in data {
for modelData in array {
var tempArray = modelData
tempArray = tempArray.filter { $0.localIdentifier != item.localIdentifier }
if tempArray.count >= 2 {
finalyVideoData.append(tempArray)
}
}
}
model.otherModelArray[index].assets = finalyVideoData
}
self?.saveToFileSystem(model: model)
})
// 将磁盘中存的内容也删除
var allImageUpdateLocation : [String] = UserDefaults.standard.object(forKey: "allImageUpdateLocationDate") as! [String]
for item in data{
allImageUpdateLocation = allImageUpdateLocation.filter { $0 != item.localIdentifier }
}
UserDefaults.standard.set(allImageUpdateLocation, forKey: "allImageUpdateLocationDate")
var screenshotUpdateLocation : [String] = UserDefaults.standard.object(forKey: "screenshotUpdateLocationDate") as! [String]
for item in data{
screenshotUpdateLocation = screenshotUpdateLocation.filter { $0 != item.localIdentifier }
}
UserDefaults.standard.set(screenshotUpdateLocation, forKey: "screenshotUpdateLocationDate")
// 将单利中的数据也删除
for item in data {
Singleton.shared.resourceModel.removeAll{ $0.ident == item.localIdentifier }
}
}
// 从文件读取
func loadFromFileSystem(filename: String = "photosManagerData.json",resultModel:@escaping (_ model:PhotosManagerModel) -> () = {mdoel in}) {
// let url = getDocumentsDirectory().appendingPathComponent(filename)
//
// // 设计缓存读取
// do {
// let data = try Data(contentsOf: url)
// let decoder = JSONDecoder()
// let model = try decoder.decode(PhotosManagerModel.self, from: data)
// resultModel(model)
// } catch {
//
// loadDataFromPhotos { model in
// resultModel(model)
// }
// }
loadDataFromPhotos { model in
let url = getDocumentsDirectory().appendingPathComponent(filename)
// 设计缓存读取
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let model = try decoder.decode(PhotosManagerModel.self, from: data)
resultModel(model)
} catch {
Print("从缓存获取数据失败")
}
}
private func loadDataFromPhotos(resultModel:@escaping (_ model:PhotosManagerModel) -> () = {mdoel in}) {
// 先存一下数据
public func loadDataFromPhotos(resultModel:@escaping (_ model:PhotosManagerModel) -> () = {mdoel in}) {
PhotoAndVideoMananger.mananger.setAssets()
......@@ -75,79 +141,94 @@ class PhotoDataManager {
let allModel:PhotosManagerModel = PhotosManagerModel(allFileNumber: 0, allFileSize: 0, titleModelArray: [model1,model2], otherModelArray: [model3,model4,model5,model6,model7])
resultModel(allModel)
Print("正在处理重复图片")
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: PhotoAndVideoMananger.mananger.allAssets, threshold: 0.99) { data1,data2 in
var dataArray1 : [AssetModel] = []
var dataArray2 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
}
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model1.assets = data1
model1.allFileSize = Double(fileSize)
resultModel(allModel)
})
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray2)!,progress: { fileSize, index in
// 不做处理
}, completion: { fileSize,index in
model2.assets = data2
model2.allFileSize = Double(fileSize)
resultModel(allModel)
})
} completionHandler: { data1, data2 in
var dataArray1 : [AssetModel] = []
var dataArray2 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
}
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model1.assets = data1
model1.allFileSize = Double(fileSize)
resultModel(allModel)
})
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSize, index in
// 不做处理
}, completion: { fileSize,index in
model2.assets = data2
model2.allFileSize = Double(fileSize)
resultModel(allModel)
})
Print("处理重复图片结束")
PhotoDataManager.manager.saveToFileSystem(model: allModel)
Print("正在处理重复和相似图片")
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: PhotoAndVideoMananger.mananger.allAssets, type: 0, threshold: 0.99) { data1,data2 in
var dataArray1 : [AssetModel] = []
var dataArray2 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
}
// 视频数据
Print("正在处理视频")
PhotoAndVideoMananger.mananger.dealVideoData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model3.assets = data
model3.allFileSize = Double(fileSize)
resultModel(allModel)
Print("处理视频结束")
})
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model1.assets = data1
model1.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeDupImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray2)!,progress: { fileSize, index in
// 不做处理
}, completion: { fileSize,index in
model2.assets = data2
model2.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeSimilarImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
} completionHandler: { data1, data2 in
var dataArray1 : [AssetModel] = []
var dataArray2 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
}
// 相似截图
Print("正在处理相似截图")
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: PhotoAndVideoMananger.mananger.screenShotAssets, threshold: 0.99) { data1,data2 in
for item in data2 {
dataArray2 = dataArray2 + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model1.assets = data1
model1.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeDupImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSize, index in
// 不做处理
}, completion: { fileSize,index in
model2.assets = data2
model2.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeSimilarImageResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
Print("处理重复和相似图片结束")
}
// 视频数据
Print("正在处理视频")
PhotoAndVideoMananger.mananger.dealVideoData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model3.assets = data
model3.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeVideoResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
Print("处理视频结束")
})
}
// 相似截图
Print("正在处理相似截图")
PhotoAndVideoMananger.mananger.dealSimilarPhotos(assets: PhotoAndVideoMananger.mananger.screenShotAssets, type: 1, threshold: 0.99) { data1,data2 in
var dataArray1 : [AssetModel] = []
for item in data1 {
dataArray1 = dataArray1 + item
......@@ -155,9 +236,11 @@ class PhotoDataManager {
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model4.assets = data1
model4.assets = data2
model4.allFileSize = Double(fileSize)
resultModel(allModel)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeSimilarScreenshotResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
} completionHandler: { data1, data2 in
......@@ -168,67 +251,71 @@ class PhotoDataManager {
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray1)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model4.assets = data1
model4.assets = data2
model4.allFileSize = Double(fileSize)
resultModel(allModel)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeSimilarScreenshotResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
}
// 截图数据
Print("正在处理截图")
PhotoAndVideoMananger.mananger.dealScreenShotData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model5.assets = data
model5.allFileSize = Double(fileSize)
resultModel(allModel)
Print("处理截图结束")
})
}
// 相似视频
Print("正在处理相似视频")
PhotoAndVideoMananger.mananger.fetXSVideo { array in
PhotoSimilarityFinder.processSimilarVideoGroups(videoGroups: array) {ids in
var dataArray : [AssetModel] = []
for item in ids {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model6.assets = ids
model6.allFileSize = Double(fileSize)
resultModel(allModel)
})
Print("处理相似视频结束")
}
// 截图数据
Print("正在处理截图")
PhotoAndVideoMananger.mananger.dealScreenShotData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
// 照片数据
PhotoAndVideoMananger.mananger.dealImageAssetData { data in
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model5.assets = data
model5.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeScreenShotResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
Print("处理截图结束")
})
}
// 相似视频
Print("正在处理相似视频")
PhotoAndVideoMananger.mananger.fetXSVideo { array in
PhotoSimilarityFinder.processSimilarVideoGroups(videoGroups: array) {ids in
var dataArray : [AssetModel] = []
for item in data {
for item in ids {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model7.assets = data
model7.allFileSize = Double(fileSize)
resultModel(allModel)
// 最后做一下缓存
// PhotoDataManager.manager.saveToFileSystem(model: allModel)
model6.assets = ids
model6.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeSimilarVideoResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
Print("处理相似视频结束")
}
// }
}
// 照片数据
PhotoAndVideoMananger.mananger.dealImageAssetData { data in
var dataArray : [AssetModel] = []
for item in data {
dataArray = dataArray + item
}
PhotoAndVideoMananger.mananger.calculateTotalSize(of: PhotoAndVideoMananger.mananger.getPHAsssetwithIDs(ids: dataArray)!,progress: { fileSiez, index in
// 不做处理
}, completion: { fileSize,index in
model7.assets = data
model7.allFileSize = Double(fileSize)
PhotoDataManager.manager.saveToFileSystem(model: allModel)
let dataUpdated = Notification.Name("HomeOtherResourceUpdate")
NotificationCenter.default.post(name: dataUpdated, object: nil)
})
}
}
}
......
......@@ -31,7 +31,7 @@ class HomeOtherCollectionCell: UICollectionViewCell {
}()
let countLabel: UILabel = {
public var countLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.font = .systemFont(ofSize: 10, weight: .medium)
......
......@@ -14,9 +14,9 @@ class HomeTitleCollectionCell:UICollectionViewCell {
private var titleLabel: UILabel?
private var fileLabel:UILabel?
public var fileLabel:UILabel?
private var collectionView: UICollectionView?
public var collectionView: UICollectionView?
private var nextImage:UIImageView?
......
......@@ -173,7 +173,7 @@ extension PMShowImgVideoController : UICollectionViewDelegate,UICollectionViewDa
return cell
}else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PMShowItemCellID, for: indexPath) as! PMShowItemCell
cell.icon = self.homeDataSource![indexPath.row].image!
cell.icon = self.homeDataSource![indexPath.row].image
cell.isCurrent = (self.currentIdx == indexPath.row)
return cell
}
......
......@@ -659,7 +659,41 @@ class PhotoAndVideoMananger {
// MARK: - 新方法处理相似图片向下-------------------------------------------------------
func dealSimilarPhotos(assets:[PHAsset] , threshold: Double , processHandler:@escaping ([[AssetModel]],[[AssetModel]])->Void, completionHandler:@escaping ([[AssetModel]],[[AssetModel]])->Void){
// 做一下缓存
let imageCache = NSCache<NSString, UIImage>()
/// 从缓存中找到image
/// - Parameter asset: 图片资源
/// - Returns: image
func findCacheImageByAsset(asset:PHAsset) -> UIImage?{
// 先从缓存中获取图片
var cachedImage = self.imageCache.object(forKey: asset.localIdentifier as NSString)
if cachedImage != nil{
return cachedImage
}
// 图片请求选项
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isSynchronous = true
imageRequestOptions.deliveryMode = .highQualityFormat
// 缓存没有再去加载下
PHImageManager.default().requestImage(for: asset, targetSize: CGSizeMake(400, 400), contentMode: .aspectFit, options: imageRequestOptions) {image, info in
if image != nil {
// 存入缓存
self.imageCache.setObject(image!, forKey: asset.localIdentifier as NSString)
}
}
// 最后再取一次
cachedImage = self.imageCache.object(forKey: asset.localIdentifier as NSString)
return cachedImage
}
func dealSimilarPhotos(assets:[PHAsset] , type:Int, threshold: Double , processHandler:@escaping ([[AssetModel]],[[AssetModel]])->Void, completionHandler:@escaping ([[AssetModel]],[[AssetModel]])->Void){
let tempAssets = assets
DispatchQueue.global().async {
// 图片请求选项
......@@ -670,32 +704,61 @@ class PhotoAndVideoMananger {
var groupDuplicateAssets :[[AssetModel]] = []
var groupSimilarAssets :[[AssetModel]] = []
var saveFinisedArray : [String]
if type == 0 {
saveFinisedArray = UserDefaults.standard.object(forKey: "allImageUpdateLocationDate") as? [String] ?? []
}else{
saveFinisedArray = UserDefaults.standard.object(forKey: "screenshotUpdateLocationDate") as? [String] ?? []
}
for (currentIndex, currentAsset) in assets.enumerated() {
for (currentIndex, currentAsset) in tempAssets.enumerated() {
// 去重
let uniqueArray = saveFinisedArray.reduce(into: [String]()) { result, element in
if !result.contains(element) {
result.append(element)
}
}
saveFinisedArray = uniqueArray
// 判断是否已经处理过了
if saveFinisedArray.contains(currentAsset.localIdentifier){
continue
}
var currentDuplicateGroup : [AssetModel] = []
var currentSimilarGroup : [AssetModel] = []
// 先添加一个到model
let currentModel = AssetModel.init(localIdentifier: currentAsset.localIdentifier, assetSize: PhotoAndVideoMananger.mananger.findAssetSize(asset: currentAsset), createDate: currentAsset.creationDate!)
currentDuplicateGroup.append(currentModel)
PHImageManager.default().requestImage(for: currentAsset, targetSize: CGSizeMake(400, 400), contentMode: .aspectFit, options: imageRequestOptions) {image1, info1 in
let nextIndex = currentIndex + 1
if nextIndex <= assets.count {
for changeIndex in nextIndex..<assets.count {
let changeAsset = assets[changeIndex]
PHImageManager.default().requestImage(for: changeAsset, targetSize: CGSizeMake(400, 400), contentMode: .aspectFit, options: imageRequestOptions) {image2, info2 in
let isSamilar : Double = OpenCVWrapper.compareImageSimilarity(image1, withImage2: image2)
let image1 = self.findCacheImageByAsset(asset: currentAsset)
// 如果取出的image是空的跳过这次循环
if image1 == nil {
continue
}
if isSamilar > 0.995 && isSamilar < 0.996{
currentSimilarGroup.append(AssetModel(localIdentifier: changeAsset.localIdentifier, assetSize: self.findAssetSize(asset: changeAsset), createDate: changeAsset.creationDate!))
}
if isSamilar > 0.999 {
currentDuplicateGroup.append(AssetModel(localIdentifier: changeAsset.localIdentifier, assetSize: self.findAssetSize(asset: changeAsset), createDate: changeAsset.creationDate!))
}
}
let nextIndex = currentIndex + 1
if nextIndex <= tempAssets.count {
for changeIndex in nextIndex..<tempAssets.count {
// 判断是否已经处理过了
if saveFinisedArray.contains(tempAssets[changeIndex].localIdentifier){
continue
}
let changeAsset = tempAssets[changeIndex]
let image2 = self.findCacheImageByAsset(asset: changeAsset)
if image2 == nil {
continue
}
let isSamilar : Double = OpenCVWrapper.compareImageSimilarity(image1, withImage2: image2)
if isSamilar > 0.999 {
currentDuplicateGroup.append(AssetModel(localIdentifier: changeAsset.localIdentifier, assetSize: self.findAssetSize(asset: changeAsset), createDate: changeAsset.creationDate!))
saveFinisedArray.append(currentAsset.localIdentifier)
}
if isSamilar > 0.995 && isSamilar < 0.996{
currentSimilarGroup.append(AssetModel(localIdentifier: changeAsset.localIdentifier, assetSize: self.findAssetSize(asset: changeAsset), createDate: changeAsset.creationDate!))
saveFinisedArray.append(currentAsset.localIdentifier)
}
}
if(currentSimilarGroup.count >= 2){
groupSimilarAssets.append(currentSimilarGroup)
......@@ -703,35 +766,27 @@ class PhotoAndVideoMananger {
if(currentDuplicateGroup.count >= 2){
groupDuplicateAssets.append(currentDuplicateGroup)
}
processHandler(groupDuplicateAssets,groupSimilarAssets)
if currentSimilarGroup.count >= 2 || currentDuplicateGroup.count >= 2 {
// 更新回调
processHandler(groupDuplicateAssets,groupSimilarAssets)
}
}
saveFinisedArray.append(currentAsset.localIdentifier)
if type == 0 {
UserDefaults.standard.set(saveFinisedArray , forKey: "allImageUpdateLocationDate")
}else{
UserDefaults.standard.set(saveFinisedArray, forKey: "screenshotUpdateLocationDate")
}
}
// 全部请求结束之后,清理下缓存
self.imageCache.removeAllObjects()
// 完成回调
completionHandler(groupDuplicateAssets,groupSimilarAssets)
}
// // 重复照片
// var index = assets.startIndex
// var count = 0
// var finalData :[[AssetModel]] = []
// while index < assets.endIndex {
// let nextIndex = assets.index(index, offsetBy: 5, limitedBy: assets.endIndex) ?? assets.endIndex
// // 当前组
// let chunk = Array(assets[index..<nextIndex])
// index = nextIndex
//
// dealSimilarDetailPhotos(assets: chunk as [PHAsset], allAssets: assets, threshold: threshold) { data in
// count = count + chunk.count
// finalData = finalData + data
// if count == assets.count {
// completionHandler(finalData)
// }
// }
// }
}
......@@ -749,102 +804,6 @@ class PhotoAndVideoMananger {
return Double(assetSize)
}
// 和上面的方法一起处理,防止内存崩溃
private func dealSimilarDetailPhotos(assets:[PHAsset],allAssets:[PHAsset],threshold: Double , completionHandler:@escaping ([[AssetModel]])->Void){
var groupAssets :[[AssetModel]] = []
// 图片请求选项
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.deliveryMode = .highQualityFormat
imageRequestOptions.isSynchronous = true
imageRequestOptions.resizeMode = .exact
imageRequestOptions.isNetworkAccessAllowed = true
// 开一个线程去处理
// DispatchQueue.global().async {
// 需要监听是否完成
var count1 = 0
for asset in assets {
PHImageManager.default().requestImage(for: asset, targetSize: CGSizeMake(50, 50), contentMode: .aspectFit, options: imageRequestOptions) { [self] image1, info in
var currentGroup : [AssetModel] = []
// 如果当前组为空,先加一个上去
currentGroup.append(AssetModel(localIdentifier: asset.localIdentifier, assetSize: self.findAssetSize(asset: asset), createDate: asset.creationDate!))
// 然后分成区域比较
var index = assets.startIndex
var count2 = 0
while index < allAssets.endIndex {
let nextIndex = assets.index(index, offsetBy: 10, limitedBy: allAssets.endIndex) ?? allAssets.endIndex
// 当前组
var chunk = Array(allAssets[index..<nextIndex])
index = nextIndex
// 比较image重复
for item in chunk {
// 获取到当前图片
PHImageManager.default().requestImage(for: item, targetSize: CGSizeMake(50, 50), contentMode: .aspectFit, options: imageRequestOptions) { image2, info in
let isSamilar : Bool = OpenCVWrapper.areImagesSimilar(image1, withImage2: image2, threshold: threshold)
// 如果相似或者相同
if isSamilar {
currentGroup.append(AssetModel(localIdentifier: item.localIdentifier, assetSize: self.findAssetSize(asset: item), createDate: item.creationDate!))
}
}
}
// 将trunk移除
count2 = count2 + chunk.count
if count2 == allAssets.count {
// 对当前组去重
let result = removeDuplicates(currentGroup)
if(result.count >= 2){
groupAssets.append(currentGroup)
}
}
chunk.removeAll(keepingCapacity: false)
}
currentGroup.removeAll(keepingCapacity: false)
}
count1 = count1 + 1
if count1 == assets.count {
completionHandler(self.removeDuplicatesIn2DArray(groupAssets, keyPath: \.localIdentifier))
}
}
// }
}
// 去掉一维数组重复数据
func removeDuplicates(_ array: [AssetModel]) -> [AssetModel] {
var uniqueLocalIdentifiers: [String] = []
var uniqueModel: [AssetModel] = []
for model in uniqueModel {
if !uniqueLocalIdentifiers.contains(model.localIdentifier) {
uniqueLocalIdentifiers.append(model.localIdentifier)
uniqueModel.append(model)
}
}
return uniqueModel
}
/// 去掉数据重复
/// - Parameter array: 当前数据
/// - Returns: 去重后的数据
func removeDuplicatesIn2DArray<T: Hashable>(_ array: [[AssetModel]], keyPath: KeyPath<AssetModel, T>) -> [[AssetModel]] {
return array.map { innerArray in
var seen = Set<T>()
return innerArray.filter {
if seen.contains($0[keyPath: keyPath]) {
return false
} else {
seen.insert($0[keyPath: keyPath])
return true
}
}
}
}
// MARK: - 新方法处理相似图片向上-------------------------------------------------------
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment