cdn加載lottle動畫(Image)

CDN上傳

將Lottle資源打成zip包上傳到云端(七牛)簡單上傳

本地工程處理

  • 工程安裝依賴:
    坑 如果是OC工程使用swift版lottie,無法直接使用,需要進行swift封裝,在進行@objcMembers文件修飾
  pod 'lottie-ios' ,'3.2.3'
  pod 'AFNetworking'
  pod 'SSZipArchive'
  pod 'SnapKit'
  • 封裝HLAnimationImageView供OC使用(swift 可直接使用)
    AnimationView 是可以加載l沙盒lottle.json && image
    Animation 直接加載bundle的lottle.json 或 lottle.json && image, 或沙盒的lottle.json ,但無法引用沙盒圖片
import UIKit
import SnapKit
import Lottie
@objcMembers
public class HLAnimationImageView : UIView {
    /// 動畫
    public var animationView = AnimationView()
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    public init(frame: CGRect,filepath: String) {
        super.init(frame: frame)
        animationView = AnimationView.init(filePath: filepath)
        animationView.contentMode = .scaleToFill
        addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 是否是循環播放動畫
    public var loopAnimation: Bool {
        set {
            if newValue {
                animationView.loopMode = .loop
            } else {
                animationView.loopMode = .playOnce
            }
            animationView.backgroundBehavior = .pauseAndRestore
        }
        get {
            if animationView.loopMode == .loop {
                return true
            }
            return false
        }
    }
    /// 繼續播放
    public func kep_play() {
        layoutIfNeeded()
        animationView.play()
    }
    /// 暫停
    public func kep_pause() {
        animationView.pause()
    }
    /// 停止
    public func kep_stop() {
        animationView.stop()
    }
}

下載圖片解壓縮,lottle播放

- (void)downloadLottleWithZipUrlStr:(NSString *)zipString complete:(void (^)(NSURL *, NSError *))complete {
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:zipString]];
  AFURLSessionManager *session = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDownloadTask *downTask = [session downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@",downloadProgress.localizedDescription);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:response.suggestedFilename];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        return url;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error == nil) {
            if (complete) {
                complete(filePath, nil);
            }
        } else {
            if (complete) {
                complete(nil, error);
            }
        }
    }];
    [downTask resume];
}
- (void)unzipUrlStr:(NSString *)zipString complete:(void (^)(NSString *, NSError *))complete {
    
    [self downloadLottleWithZipUrlStr:zipString complete:^(NSURL *fileUrl, NSError *error) {
        if (error != nil) {
            !complete?: complete(nil, error);
            return ;
        }
        NSString *zipPath = fileUrl.absoluteString;
        zipPath = [zipPath stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSString *destinationPath = [self destinationPath];
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:destinationPath]) {
            NSError *error = nil;
            [manager createDirectoryAtPath:destinationPath withIntermediateDirectories:true attributes:nil error:&error];
            if (error != nil) {
                !complete?: complete(nil, error);
                return ;
            }
        }
        BOOL flag = [SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
        if (flag) {
            NSLog(@"true");
            if (complete) {
                complete(destinationPath, nil);
                // 解壓縮文件成功后自動刪除 zip壓縮包
                [manager removeItemAtPath:zipPath error:nil];
            }
        } else {
            NSLog(@"false");
            if (complete) {
                complete(nil, [NSError errorWithDomain:@"解壓失敗" code:300 userInfo:@{@"zipPath" : fileUrl}]);
            }
        }
    }];
}

- (NSString *)destinationPath {
    if (_destinationPath.length == 0) {
        NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"abcd"];
        return path;
    }
    return _destinationPath;
}

加載使用
lottle.json 的目錄地址必須對應上,否則無法加載出圖片

        let requestUrl = "https://xxxx.lottle.zip"
        manager?.destinationPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/lotties"
        manager?.unzipUrlStr(requestUrl, complete: { (filePath, error) in
            if (error == nil) {
                let filePath2 = filePath! + "/xxxx/lottle.json"
                let hitHighDisplayView = KEPAnimationImageView.init(frame: self.view.bounds, filepath: filePath2)
                hitHighDisplayView.frame = self.view.bounds;
                self.view.addSubview(hitHighDisplayView)
                hitHighDisplayView.loopAnimation = false
                hitHighDisplayView.backgroundColor = UIColor.blue
                hitHighDisplayView.kep_play()
            }
        })
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • C語言相關面試題 1.static有什么用途? 答案:在C語言中,static主要定義全局靜態變量,定義局部靜態變...
    Leeson1989閱讀 2,301評論 0 20
  • 1.ios高性能編程 (1).內層 最小的內層平均值和峰值(2).耗電量 高效的算法和數據結構(3).初始化時...
    歐辰_OSR閱讀 29,566評論 8 265
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,592評論 28 53
  • 信任包括信任自己和信任他人 很多時候,很多事情,失敗、遺憾、錯過,源于不自信,不信任他人 覺得自己做不成,別人做不...
    吳氵晃閱讀 6,222評論 4 8
  • 步驟:發微博01-導航欄內容 -> 發微博02-自定義TextView -> 發微博03-完善TextView和...
    dibadalu閱讀 3,167評論 1 3