123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321 |
- //
- // TSCommonTool.swift
- // TSLiveWallpaper
- //
- // Created by 100Years on 2024/12/20.
- //
- import Kingfisher
- import Foundation
- import AVFoundation
- class TSCommonTool {
- //
- // static func downLoadImage(_ urlStr:String, completion: @escaping (_ image:UIImage) -> Void) {
- // ImageDownloader.default.downloadImage(with: URL(string: urlStr)!, options: nil) { receivedSize, totalSize in
- // debugPrint(receivedSize)
- // } completionHandler: {
- // result in
- // switch result {
- // case .success(let value):
- // completion(value.image)
- // case .failure(let error):
- // print(error)
- // }
- // }
- // }
- //
-
- /// 下载图片,优先从缓存中取,支持设置缓存策略
- /// - Parameters:
- /// - url: 图片的 URL 地址
- /// - completion: 完成回调,返回图片或错误
- static func fetchImageWithCache(
- from urlString: String,
- completion: @escaping (UIImage?, Error?) -> Void
- ) {
-
- guard let url = URL(string: urlString) else{
- completion(nil, NSError(domain: "url null", code: 0))
- return
- }
- // 配置 Kingfisher 的缓存策略
- let options: KingfisherOptionsInfo = [
- .cacheOriginalImage,
- .memoryCacheExpiration(.days(7)), // 内存缓存时间
- .diskCacheExpiration(.days(30)), // 磁盘缓存时间
- .cacheSerializer(DefaultCacheSerializer.default)
- ]
-
- // 使用 Kingfisher 检查缓存是否存在
- let cache = ImageCache.default
- let cacheKey = url.absoluteString
-
- cache.retrieveImage(forKey: cacheKey, options: nil) { result in
- switch result {
- case .success(let value):
- if let image = value.image {
- // 从缓存中取到图片
- completion(image, nil)
- } else {
- // 缓存中不存在图片,进行下载
- downloadImage(from: url, options: options, completion: completion)
- }
- case .failure(let error):
- // 缓存检查失败,直接下载
- print("缓存检查失败: \(error.localizedDescription)")
- downloadImage(from: url, options: options, completion: completion)
- }
- }
- }
-
-
- /// 获取已缓存的磁盘图片文件路径
- /// - Parameters:
- /// - urlString: 图片的 URL 地址
- /// - completion: 完成回调,返回图片的磁盘路径或错误
- static func fetchImagePathWithCache(
- from urlString: String,
- completion: @escaping (String?, Error?) -> Void
- ) {
- guard let url = URL(string: urlString) else {
- completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: [NSLocalizedDescriptionKey: "无效的 URL"]))
- return
- }
-
- let cache = ImageCache.default
- let cacheKey = url.absoluteString
- if cache.isCached(forKey: cacheKey) {
- completion(cache.cachePath(forKey: cacheKey), nil)
- }else {
- completion(nil, NSError(domain: "CachePathError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取缓存路径"]))
- }
- }
-
- /// 下载图片并缓存
- /// - Parameters:
- /// - url: 图片的 URL 地址
- /// - options: Kingfisher 下载和缓存的选项
- /// - completion: 完成回调,返回图片或错误
- static func downloadImage(
- from url: URL,
- options: KingfisherOptionsInfo,
- completion: @escaping (UIImage?, Error?) -> Void
- ) {
- KingfisherManager.shared.retrieveImage(with: url, options: options,progressBlock: { receivedSize, totalSize in
- debugPrint(receivedSize)
- }) { result in
- switch result {
- case .success(let value):
- completion(value.image, nil)
- case .failure(let error):
- completion(nil, error)
- }
- }
- }
-
-
-
- /// 下载并缓存文件,依据 URL 的后缀名动态设置文件名
- /// - Parameters:
- /// - url: 文件的 URL 地址
- /// - completion: 完成回调,返回本地缓存路径或错误
- static func downloadAndCacheFile(from urlString: String, fileEx:String? = nil, cacheDirectory:String = "cacheVideo",completion: @escaping (String?, Error?) -> Void) {
-
- guard let url = URL(string: urlString) else{
- completion(nil, NSError(domain: "url null", code: 0))
- return
- }
-
-
- if !urlString.contains("http") && urlString.contains("/"){
- completion(urlString.fillCachePath, nil)
- return
- }
-
- let fileManager = FileManager.default
-
- // 获取缓存目录下的 `cacheVideo` 文件夹路径
- let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
- let cacheVideoDirectory = cacheDirectory.appendingPathComponent("cacheVideo")
-
- // 创建 `cacheVideo` 文件夹(如果不存在)
- if !fileManager.fileExists(atPath: cacheVideoDirectory.path) {
- do {
- try fileManager.createDirectory(at: cacheVideoDirectory, withIntermediateDirectories: true, attributes: nil)
- } catch {
- completion(nil, error)
- return
- }
- }
-
- // 使用 URL 的 MD5 哈希值作为缓存文件名,附加 URL 的后缀名
- var fileExtension = fileEx
- fileExtension = fileExtension ?? (url.pathExtension.isEmpty ? "tmp" : url.pathExtension)
-
-
- let fileName = url.path.md5 + ".\(fileExtension!)"
- let cachedFileURL = cacheVideoDirectory.appendingPathComponent(fileName)
-
- // 检查文件是否已存在于缓存中
- if fileManager.fileExists(atPath: cachedFileURL.path) {
- print("文件已存在于缓存中: \(cachedFileURL)")
- completion(cachedFileURL.path, nil)
- return
- }
-
- // 下载文件
- let task = URLSession.shared.downloadTask(with: url) { tempFileURL, response, error in
- if let error = error {
- completion(nil, error)
- return
- }
-
- guard let tempFileURL = tempFileURL else {
- completion(nil, NSError(domain: "DownloadError", code: -1, userInfo: [NSLocalizedDescriptionKey: "临时文件路径不存在"]))
- return
- }
-
- do {
- try fileManager.moveItem(at: tempFileURL, to: cachedFileURL)
- print("文件下载并缓存成功: \(cachedFileURL)")
- completion(cachedFileURL.path, nil)
- } catch {
- completion(nil, error)
- }
- }
-
- task.resume()
- }
- }
- let kMainQueue = DispatchQueue.main
- let appid = "6740220736"
- let kAppName:String = "Picguru" //Picguru Chibii Chibi Ghiblii AI Image Picguru
- let kUploadImageMaxBit10Size:Int = 10 * 1024 * 1024 //10M
- let kUploadImageMaxBit5Size:Int = 5 * 1024 * 1024 //5M
- func kShareContent(target: UIViewController,anyData:Any) {
-
- let text = "Turn yourself into a Ghibli style with AI magic! 🎨✨ This app creates stunning anime, cyberpunk & more—just upload a photo. Try it now!"
- kShareContent(target: target, anyData: anyData, text: text)
-
- // shareApplication(target: target)
- }
- //func kShareContent(target: UIViewController,image:UIImage?,text:String?) {
- //
- // let url = URL(string: "https://apps.apple.com/app/id\(appid)")
- //
- // let provider = CustomActivityItemProvider(image: image, text: text, url: url)
- // let vc = UIActivityViewController(activityItems: [provider], applicationActivities: nil)
- // vc.completionWithItemsHandler = { activity, _, _, _ in
- // switch activity {
- // case .copyToPasteboard:
- // UIPasteboard.general.string = text
- // default:
- // dePrint("")
- // }
- //// if let type = activity, type == .copyToPasteboard {
- //// UIPasteboard.general.string = text
- //// }else
- // }
- //
- // if UIDevice.current.userInterfaceIdiom == .pad {
- // vc.modalPresentationStyle = .popover
- // vc.popoverPresentationController?.sourceView = target.view
- // vc.popoverPresentationController?.sourceRect = target.view.bounds
- // }
- //
- // target.present(vc, animated: true)
- //}
- func kShareContent(target: UIViewController,anyData:Any?,text:String?) {
- //
- // let url = URL(string: "https://apps.apple.com/app/id\(appid)")
- // ShareHelper.share(
- // image: image,
- // text: text,
- // url: url,
- // from: target,
- // sourceView: target.view // 可以是按钮或其他UIView
- // )
- // return
- let urlString = "https://apps.apple.com/app/id\(appid)"
- var activityItems:[Any] = []
- if let anyData = anyData {
- activityItems.append(anyData)
- }
-
- if let text = text {
- activityItems.append(text+"\nApp:"+urlString)
- }
-
- // if let url = URL(string: "https://apps.apple.com/app/id\(appid)") {
- // activityItems.append(url)
- // }
-
- if activityItems.isEmpty {
- return
- }
- let vc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
- vc.completionWithItemsHandler = { activity, _, _, _ in
- switch activity {
- case .copyToPasteboard:
- UIPasteboard.general.string = text
- default:
- dePrint("")
- }
- }
- if UIDevice.current.userInterfaceIdiom == .pad {
- vc.modalPresentationStyle = .popover
- vc.popoverPresentationController?.sourceView = target.view
- vc.popoverPresentationController?.sourceRect = target.view.bounds
- }
-
- target.present(vc, animated: true)
- }
- //func shareApplication(target: UIViewController) {
- // let text = "I'm using Sweeter to decorate my phone, there are not only themes, wallpapers, widgets, but also dynamic island and super useful tools, come and try with me!"
- // let httpAppStoreLink = "https://apps.apple.com/app/id\(appid)"
- // let url = URL(string: httpAppStoreLink)!
- // let image = UIImage(named: "App-Icon")!.compressImageSize(to: CGSize(width: 100, height: 100))
- // let vc = UIActivityViewController(activityItems: [image, text, url], applicationActivities: nil)
- // vc.completionWithItemsHandler = { activity, value, _, error in
- // if let type = activity, type == .copyToPasteboard {
- // UIPasteboard.general.string = httpAppStoreLink
- // }
- // }
- // if UIDevice.current.userInterfaceIdiom == .pad {
- // vc.modalPresentationStyle = .popover
- // vc.popoverPresentationController?.sourceView = target.view
- // vc.popoverPresentationController?.sourceRect = target.view.bounds
- // }
- // target.present(vc, animated: true)
- //}
- //// todo.kailen-logo
- //func shareApp(parent: UIViewController) {
- // let httpAppStoreLink = "https://apps.apple.com/app/id\(appid)"
- // let text = "Space"
- // let url = URL(string: httpAppStoreLink)!
- // let image = UIImage.appIcon.compressImageSize(to: CGSize(width: 100, height: 100))
- // let final = ShareActivityItemProvider(placeholderItem: image)
- // let vc = UIActivityViewController(activityItems: [url, final, text], applicationActivities: nil)
- // vc.completionWithItemsHandler = { activity, _, _, _ in
- // if let type = activity, type == .copyToPasteboard {
- // UIPasteboard.general.string = httpAppStoreLink
- // }
- // }
- //
- // parent.present(vc, animated: true)
- //
- //}
|