iOS处理lottie-ios 文件管理

使用背景

项目中需要使用lottie动画库处理礼物特效相关的流程,通过服务端下发json或者zip ,iOS 的这个
思路 : 礼物管理id文件夹/data.json images 礼物id文件夹 /data.json 来管理 具体原因是lottie-ios下加载json和资源是通过 BundleImageProvider 来加载的 (这块在framwork中有点小缺陷 测试下路径试了相对路径和绝对路径始终有问题 而且json如果是在framewrok中必须放在bundle中,但打包会有问题 才疏学浅有些编译错误是真不好处理)因此客户端管理下特效相关的资源

代码实现

#######下载使用moya 解压使用ZipArchive或者 Zip

//
//  LottieResourceManager.swift
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import Foundation
import ZipArchive
import Moya
import Lottie
typealias lottieResultBlock = (_ jsonfullpath:String?,_ provider:BundleImageProvider?) -> Void
class LottieResourceManager:NSObject {
    let   filepath  = NSHomeDirectory() + "/Documents/LiveKit/GiftFile"
    static  let  shared = LottieResourceManager()
    override init() {
        super.init()
        if FileManager.default.fileExists(atPath: filepath) {
            print("礼物 目录存在")
        }
        else{
            try! FileManager.default.createDirectory(atPath: filepath,
                                                     withIntermediateDirectories: true, attributes: nil)
        }
        print(filepath)
    }
    /// 加载lottie特效
    /// - Parameters:
    ///   - giftId: 特效id
    ///   - downloadurl: 特效下载地址
    ///   - animationresult: 特效 images目录
    func  loadBundleProvider(_ giftId:Int , _ downloadurl:String ,_ animationresult:@escaping lottieResultBlock ) {
        let fullpath = filepath + "/\(giftId)/data.json"
        let imgprovider = filepath + "/\(giftId)/images"
        var jsonpath:String?=nil
        if FileManager.default.fileExists(atPath: fullpath) {
            jsonpath = fullpath
            if  FileManager.default.fileExists(atPath: imgprovider)
            {
                let  provider = BundleImageProvider.init(bundle: Bundle.main, searchPath: imgprovider)
                animationresult(jsonpath,provider)
            }else{
                animationresult(jsonpath,nil)
            }
        }
            //网络下载 并解压
        else{
            let  giftpath = filepath + "/\(giftId)"
            let assetName =  "\(giftId)"
            jsonpath = giftpath + "/data.json"
            let  urladdress  = downloadurl
            //通过Moya进行下载
            MyServiceProvider.request(.downloadGiftLottie(downloadurl:urladdress,giftDirectoryName: assetName)) { result in
                switch result {
                case .success:
                    let localLocation: URL = DefaultDownloadDir.appendingPathComponent(assetName)
                    print("下载完毕!保存地址:\(localLocation)")
                    if  urladdress.contains(".zip") {
                        let  urlpath = URL.init(fileURLWithPath: self.filepath + "/\(giftId).zip" )
                        do {
                            
                            try       FileManager.default.createDirectory(atPath: self.filepath + "/\(giftId)", withIntermediateDirectories: true, attributes: nil)
                            
                            let ziptool  = ZipArchive.init()
                            if  ziptool.unzipOpenFile( self.filepath + "/\(giftId).zip") {
                                let  res =    ziptool.unzipFile(to: giftpath, overWrite: true)
                                if !res {
                                    ziptool.unzipCloseFile()
                                }
                                
                            }
                            //                        let  zipurl =  try Zip.unzipFile(urlpath, destination: URL.init(fileURLWithPath: giftpath), overwrite: true, password: nil)
                            //得到正确的资源包  12312/ data images
                            if  FileManager.default.fileExists(atPath: imgprovider)
                            {
                                let  provider = BundleImageProvider.init(bundle: Bundle.main, searchPath: imgprovider)
                                animationresult(jsonpath,provider)
                            }else{
                                animationresult(jsonpath,nil)
                            }
                            
                            //                        print(zipurl)
                        } catch (let err) {
                            print("解压失败")
                            animationresult(nil,nil)
                            
                        }
                    }
                        
                    else if urladdress.contains(".json") {
                        do {
                            
                            try       FileManager.default.createDirectory(atPath: self.filepath + "/\(giftId)", withIntermediateDirectories: true, attributes: nil)
                            try  FileManager.default.moveItem(atPath: self.filepath + "/data.json", toPath: giftpath + "/data.json")
                            
                            animationresult(jsonpath,nil)
                            
                            
                            //                        print(zipurl)
                        } catch (let err) {
                            debugPrint("文件出错\(err)")
                            animationresult(nil,nil)
                            
                        }
                        
                    }
                    
                    
                case let .failure(error):
                    print(error)
                    animationresult(nil,nil)
                }
            }
        }
    }
    
    
}

//MARK:单独组件处理下载


//初始化请求的provider
let MyServiceProvider = MoyaProvider()

//请求分类
public enum DownLoadService {
    case downloadGiftLottie(downloadurl:String,giftDirectoryName:String) //下载文件
}

//请求配置
extension DownLoadService: TargetType {
    public var path: String {
        return ""
    }
    
    //服务器地址
    public var baseURL: URL {
        switch self {
        case .downloadGiftLottie(let  url , _ ):
            return URL.init(string: url)!
            
        default:
            return URL(string: "http://www.baidu.com")!
        }
    }
    //请求类型
    public var method: Moya.Method {
        return .get
    }
    
    //请求任务事件(这里附带上参数)
    public var task: Task {
        switch self {
        case .downloadGiftLottie(let  downloadurl ,let saveName):
            var localLocation: URL!
            if downloadurl.contains(".zip") {
                localLocation = DefaultDownloadDir.appendingPathComponent(saveName+".zip")
            }else if downloadurl.contains(".json") {
                
                localLocation = DefaultDownloadDir.appendingPathComponent("data.json")
            }
            //
            
            let downloadDestination:DownloadDestination = { _, _ in
                
                return (localLocation, .removePreviousFile) }
            return .downloadDestination(downloadDestination)
        }
        
    }
    
    //是否执行Alamofire验证
    public var validate: Bool {
        return false
    }
    
    //这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
    public var sampleData: Data {
        return "{}".data(using: String.Encoding.utf8)!
    }
    
    //请求头
    public var headers: [String: String]? {
        return nil
    }
}

//定义下载的DownloadDestination(不改变文件名,同名文件不会覆盖)
private let DefaultDownloadDestination: DownloadDestination = { temporaryURL, response in
    return (DefaultDownloadDir.appendingPathComponent(response.suggestedFilename!), [.removePreviousFile])
}

//默认下载保存地址(用户文档目录)
let DefaultDownloadDir: URL = {
    
    return  URL(fileURLWithPath: LottieResourceManager.shared.filepath)
}()

使用方式(当然可以基于这个封装更好的使用方式)

           LottieResourceManager.shared.loadBundleProvider(123412, "http://file.ds.net.cn:28080/live/unknown/20200701/3C553D07930C3998D667772BF29B8944/3C553D07930C3998D667772BF29B8944.json") {[weak self] (jsonpath, provider) in
                guard let `self` = self else {return}
                guard let  jsonfile = jsonpath else{return}
                self.animationView = AnimationView.init(filePath:jsonfile)
                if let  prov = provider {
                    self.animationView.imageProvider = prov
                }
                self.view.addSubview(self.animationView)
                self.animationView.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.size.height)
                self.animationView.play()
            }

你可能感兴趣的:(iOS处理lottie-ios 文件管理)