Ver código fonte

将Kingfisher的默认Cache文件夹,移动到document

100Years 2 semanas atrás
pai
commit
0645abf097

+ 73 - 5
TSLiveWallpaper/AppDelegate.swift

@@ -101,11 +101,7 @@ extension AppDelegate {
         TSColorConfigShared.naviMianTextColor = .white//设置基类颜色
 //        _ = TSImageDataCenter.shared
         
-        //设置Kingfisher缓存规则
-        let cache = ImageCache(name: "permanent_image_cache")
-        cache.diskStorage.config.expiration = .never    // 永不过期
-        cache.diskStorage.config.sizeLimit = 0          // 无大小限制
-        KingfisherManager.shared.cache = cache
+        handleKingfisher()
 
         checkAppConfig()
         
@@ -131,3 +127,75 @@ extension AppDelegate {
 
 
 }
+extension AppDelegate {
+    
+    func handleKingfisher(){
+    
+//        let documentURL = FileManager.default.urls(
+//            for: .documentDirectory,
+//            in: .userDomainMask
+//        ).first!
+//        
+//        let cache = try! ImageCache(
+//            name: "permanent_image_cache",
+//            cacheDirectoryURL: libraryURL
+//        )
+        
+        
+        moveCacheSmoothly()
+        
+        let cache = ImageCache(
+            name: "permanent_image_cache"
+        )
+        cache.diskStorage.config.expiration = .never    // 永不过期
+        cache.diskStorage.config.sizeLimit = 0          // 无大小限制
+        KingfisherManager.shared.cache = cache
+        
+    }
+    
+    
+    func moveCacheSmoothly(){
+        // 1. 获取旧文件路径的图片
+        let fileManager = FileManager.default
+        guard let cachesURL = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
+            dePrint("Cache Kingfisher 没有缓存,不用迁移")
+            return
+        }
+        let srcURL = cachesURL.appendingPathComponent("com.onevcat.Kingfisher.ImageCache.permanent_image_cache")
+        guard fileManager.fileExists(atPath: srcURL.path) else { return }
+        
+        //把srcURL 移动到新的 documentURL
+        guard let documentURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
+        let dstURL = documentURL.appendingPathComponent("KingfisherCache")
+        
+        // 4. 处理目标已存在的情况
+        if fileManager.fileExists(atPath: dstURL.path) {
+            do {
+                // 先删除目标文件夹(如果需要合并则改为遍历子文件)
+                try fileManager.removeItem(at: dstURL)
+                dePrint("已清理旧缓存目录")
+            } catch {
+                dePrint("清理旧缓存失败: \(error.localizedDescription)")
+                return
+            }
+        }
+        
+        do {
+              try fileManager.createDirectory(at: dstURL, withIntermediateDirectories: true, attributes: nil)
+          } catch {
+              dePrint("创建目录失败: \(error.localizedDescription)")
+              return
+          }
+        
+        do {
+            dePrint("srcURL=\(srcURL)")
+            dePrint("dstURL=\(dstURL)")
+//            try fileManager.copyItem(at: srcURL, to: dstURL)
+            try fileManager.moveItem(at: srcURL, to: dstURL)// 移动文件
+        } catch {
+            debugPrint("尝试移动文件失败: \(error.localizedDescription)")
+        }
+        
+        dePrint("移动 Cache Kingfisher 到 library 流程结束")
+    }
+}

+ 6 - 3
TSLiveWallpaper/Business/TSAIListVC/TSAIPhotoDetailsVC/TSAIPhotoDetailsBrowserCell.swift

@@ -10,7 +10,7 @@ class TSAIPhotoDetailsBaseBrowserCell: TSBaseCollectionCell {
     var model:TSActionInfoModel = TSActionInfoModel()
 }
 
-class TSAIPhotoDetailsPanComparisonViewCell: TSAIPhotoDetailsBaseBrowserCell {
+class TSAIPhotoDetailsPanComparisonViewCell: TSAIPhotoDetailsImageViewCell {
     override var model:TSActionInfoModel{
         didSet{
             uploadPanComparisonView()
@@ -19,6 +19,7 @@ class TSAIPhotoDetailsPanComparisonViewCell: TSAIPhotoDetailsBaseBrowserCell {
     
     lazy var panComparisonView : TSImageIPanComparisonView = TSImageIPanComparisonView()
     override func creatUI() {
+        super.creatUI()
         bgContentView.addSubview(panComparisonView)
         panComparisonView.snp.makeConstraints { make in
             make.height.equalTo(k_ScreenHeight)
@@ -53,9 +54,11 @@ class TSAIPhotoDetailsPanComparisonViewCell: TSAIPhotoDetailsBaseBrowserCell {
                     self.panComparisonView.snp.updateConstraints { make in
                         make.height.equalTo(kGetUIWdith(designSize: size, currentW: k_ScreenWidth))
                     }
+                    self.panComparisonView.configure(oldImage: oldImage, newImage: newImage)
+                }else if let newImage = newImage{
+                    self.panComparisonView.isHidden = true
+                    self.netWorkImageView.image = newImage
                 }
-                
-                self.panComparisonView.configure(oldImage: oldImage, newImage: newImage)
             }
         }
     }

+ 4 - 4
TSLiveWallpaper/Business/TSAIListVC/TSAIPhotoDetailsVC/TSAIPhotoDetailsBrowserVC.swift

@@ -27,7 +27,7 @@ class TSAIPhotoDetailsBrowserVC: TSBaseVC {
 
         let layout = UICollectionViewFlowLayout()
         layout.scrollDirection = .vertical
-        
+        layout.itemSize = UIScreen.main.bounds.size
         let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
         collectionView.delegate = self
         collectionView.dataSource = self
@@ -128,9 +128,9 @@ class TSAIPhotoDetailsBrowserVC: TSBaseVC {
             self.collectionView.reloadData()
             self.collectionView.setContentOffset(CGPoint(x:0 , y:CGFloat(self.currentIndex) * self.collectionView.frame.size.height), animated: false)
 
-            if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
-                flowLayout.itemSize = self.collectionView.bounds.size
-            }
+//            if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
+//                flowLayout.itemSize = self.collectionView.bounds.size
+//            }
             self.reloadUI()
         }
     }

+ 2 - 18
TSLiveWallpaper/Common/Purchase/TSPurchaseBusiness+Limit.swift

@@ -76,13 +76,7 @@ extension TSPurchaseBusiness {
             dict = saveDict
         }
         dict[type.rawValue] = ["date": Date().dateDayString, "times": dayNum]
-        UserDefaults.standard.set(dict, forKey: kDayGeneratedNumKey)
-        UserDefaults.standard.synchronize()
-        //保存到钥匙串
-        if let jsonString = dict.toJSONString() {
-            dePrint("从钥匙串存入了jsonString kDayGeneratedNumKey=\(jsonString)")
-            KeychainManager.save(jsonString, forKey: kDayGeneratedNumKey)
-        }
+        saveForUserKeychain(data: dict,key: kDayGeneratedNumKey)
     }
 
     func loadDayGeneratedNum(type: VipFreeNumType)-> Int {
@@ -106,9 +100,6 @@ extension TSPurchaseBusiness {
     //是否超出Vip期间使用的次数
     public func isExceedsVipGeneratedNum(vipFreeNumType:VipFreeNumType) -> Bool {
         if isVip {
-//            #if DEBUG
-//            return false
-//            #endif
             let dayNum = loadVipGeneratedNum(type: vipFreeNumType)
             if vipFreeNumType == .generalVideo {
                 return dayNum >= vipType.creatVideoMaxNum
@@ -129,14 +120,7 @@ extension TSPurchaseBusiness {
             dict = saveDict
         }
         dict[type.rawValue] = ["times": dayNum,"expireTime":expireTime]
-        UserDefaults.standard.set(dict, forKey: kVipGeneratedNumKey)
-        UserDefaults.standard.synchronize()
-        //保存到钥匙串
-        if let jsonString = dict.toJSONString() {
-            dePrint("从钥匙串存入了jsonString kVipGeneratedNumKey=\(jsonString)")
-            KeychainManager.save(jsonString, forKey: kVipGeneratedNumKey)
-        }
-        
+        saveForUserKeychain(data: dict,key: kVipGeneratedNumKey)
     }
 
     func loadVipGeneratedNum(type: VipFreeNumType)-> Int {

+ 34 - 48
TSLiveWallpaper/Common/Purchase/TSPurchaseBusiness.swift

@@ -38,27 +38,17 @@ class TSPurchaseBusiness {
         }
         return time
     }
-    
-    public var isOverTotalTimes: Bool {
-        if isVip {
-            loadTotalUse()
-            return totalUsedTimes >= vipType.freeNumber
-        }
-        return false
-    }
-    
+
     /// 使用一次免费次数
     func useOnceForFree(type:VipFreeNumType){
-        /// 总使用次数
         if isVip {
+            saveForVipFreeNum(type: type)
             saveForDayGeneratedNum(type: type)
             saveForVipGeneratedNum(type: type)
         }
-        
-        if isVip {
-            return
-        }
-        
+    }
+    
+    func saveForVipFreeNum(type: VipFreeNumType){
         var freeDict = getFreeDict()
         var freeNum = freeDict[type.rawValue] ?? 0
         if freeNum > 0 {
@@ -70,8 +60,7 @@ class TSPurchaseBusiness {
         }
         
         freeDict[type.rawValue] = freeNum
-        UserDefaults.standard.set(freeDict, forKey: kFreeNumKey)
-        UserDefaults.standard.synchronize()
+        saveForUserKeychain(data: freeDict,key: kFreeNumKey)
         
         NotificationCenter.default.post(name: .kVipFreeNumChanged, object: nil, userInfo: ["VipFreeNumType": type])
     }
@@ -81,17 +70,28 @@ class TSPurchaseBusiness {
         return freeNum
     }
     
-    func loadTotalUse() {
-        // 当天没记录,设置默认次数
-        guard let dict = UserDefaults.standard.dictionary(forKey: kTotalUseNumKey),
-              dict.safeString(forKey: "date") == Date().dateDayString else {
-            totalUsedTimes = 0
-            return
+    /// 免费次数是否可用
+    func freeNumAvailable(type:VipFreeNumType) -> Bool{
+        if isVip == true {
+            return true
+        }else{
+            if let freeNum = getFreeDict()[type.rawValue],freeNum > 0 {
+                return true
+            }
         }
-        // 有记录,设置已经使用次数
-        totalUsedTimes = dict.safeInt(forKey: "times")
+        return false
     }
     
+    /// 是否展示生成类的会员图标
+    func generateVipShow(type:VipFreeNumType) -> Bool{
+        if isVip == false, freeNum(type: type) > 0 {
+            return false
+        }
+        return true
+    }
+}
+
+extension TSPurchaseBusiness{
     func initializeForFree(){
         
         if let jsonString = KeychainManager.load(forKey: kFreeNumKey, type: String.self),
@@ -129,35 +129,23 @@ class TSPurchaseBusiness {
                 VipFreeNumType.generalVideo.rawValue:1,
                 VipFreeNumType.generalRemoveBg.rawValue:1
             ]
-            UserDefaults.standard.set(dict, forKey: kFreeNumKey)
-            UserDefaults.standard.synchronize()
             return dict
         }
     }
-
-    /// 免费次数是否可用
-    func freeNumAvailable(type:VipFreeNumType) -> Bool{
-        if isVip == true {
-            return true
-        }else{
-            if let freeNum = getFreeDict()[type.rawValue],freeNum > 0 {
-                return true
-            }
-        }
-        return false
-    }
     
-    /// 是否展示生成类的会员图标
-    func generateVipShow(type:VipFreeNumType) -> Bool{
-        if isVip == false, freeNum(type: type) > 0 {
-            return false
+    func saveForUserKeychain(data:[String:Any],key:String) {
+        UserDefaults.standard.set(data, forKey: key)
+        UserDefaults.standard.synchronize()
+        
+        //保存到钥匙串
+        if let jsonString = data.toJSONString() {
+            KeychainManager.save(jsonString, forKey: key)
+            dePrint("从钥匙串存入了key=\(key),jsonString=\(jsonString)")
         }
-        return true
     }
 }
+
 extension TSPurchaseBusiness{
-    
-    
     func launchPrchase() {
         PurchaseManager.default.password = "155c8104e2b041c0abae43ace199124c"
         PurchaseManager.default.purchaseProducts = [
@@ -168,9 +156,7 @@ extension TSPurchaseBusiness{
         ]
         
         PurchaseManager.default.requestProducts()
-        
     }
-    
 }
 
 extension TSPurchaseBusiness{

+ 8 - 8
TSLiveWallpaper/Common/Purchase/TSPurchaseManager.swift

@@ -42,6 +42,14 @@ public class PurchaseManager: NSObject {
         if let info = UserDefaults.standard.object(forKey: kPremiumExpiredInfoKey) as? [String: Any] {
             vipInformation = info
         }
+        
+#if DEBUG
+    verifyPayResult(transaction: SKPaymentTransaction(), useSandBox: true)
+#else
+    verifyPayResult(transaction: SKPaymentTransaction(), useSandBox: false)
+#endif
+        
+      
     }
 
     public var expiredDate: Date? {
@@ -271,14 +279,6 @@ extension PurchaseManager: SKProductsRequestDelegate {
         DispatchQueue.main.async {
             NotificationCenter.default.post(name: .kPurchasePrepared, object: nil)
         }
-        
-#if DEBUG
-    verifyPayResult(transaction: SKPaymentTransaction(), useSandBox: true)
-#else
-    verifyPayResult(transaction: SKPaymentTransaction(), useSandBox: false)
-#endif
-        
-        
     }
 
     public func request(_ request: SKRequest, didFailWithError error: Error) {