80 lines
2.5 KiB
Swift
80 lines
2.5 KiB
Swift
//
|
||
// CloudDriveFormatter.swift
|
||
// suixinkan
|
||
//
|
||
|
||
import Foundation
|
||
import UIKit
|
||
|
||
/// 云盘展示格式化工具。
|
||
enum CloudDriveFormatter {
|
||
/// 文件类型名称。
|
||
static func typeName(_ type: Int) -> String {
|
||
switch type {
|
||
case 1:
|
||
"视频"
|
||
case 2:
|
||
"图片"
|
||
case 99:
|
||
"文件夹"
|
||
default:
|
||
"文件"
|
||
}
|
||
}
|
||
|
||
/// 文件描述。
|
||
static func fileDescription(_ file: CloudFile) -> String {
|
||
let createdDate = dateOnly(file.createdAt)
|
||
if file.isFolder {
|
||
return "\(createdDate) | \(file.childNum)个项目"
|
||
}
|
||
return "\(createdDate) | \(fileSize(file.fileSize))"
|
||
}
|
||
|
||
/// 文件大小展示。
|
||
static func fileSize(_ bytes: Int64) -> String {
|
||
guard bytes > 0 else { return "0 B" }
|
||
let units = ["B", "KB", "MB", "GB", "TB"]
|
||
var value = Double(bytes)
|
||
var index = 0
|
||
while value >= 1024, index < units.count - 1 {
|
||
value /= 1024
|
||
index += 1
|
||
}
|
||
return String(format: "%.2f %@", value, units[index])
|
||
}
|
||
|
||
/// 将后端时间转换为 Android 列表使用的 yyyy-MM-dd 日期。
|
||
static func dateOnly(_ value: String) -> String {
|
||
guard !value.isEmpty else { return "" }
|
||
if value.count >= 10 {
|
||
let endIndex = value.index(value.startIndex, offsetBy: 10)
|
||
return String(value[..<endIndex])
|
||
}
|
||
return value
|
||
}
|
||
|
||
/// URL 或文件名的后缀。
|
||
static func fileExtension(_ value: String) -> String {
|
||
let ext = URL(string: value)?.pathExtension ?? URL(fileURLWithPath: value).pathExtension
|
||
return ext.isEmpty ? typeName(0) : ext.uppercased()
|
||
}
|
||
}
|
||
|
||
/// 云盘 Android 同名图片资源访问工具。
|
||
enum CloudDriveAsset {
|
||
/// 返回云盘图片资源,缺失时使用系统图标兜底。
|
||
static func image(named name: String, fallbackSystemName: String) -> UIImage? {
|
||
UIImage(named: name)?.withRenderingMode(.alwaysOriginal) ?? UIImage(systemName: fallbackSystemName)
|
||
}
|
||
|
||
/// 返回缩放到指定点尺寸的云盘图标。
|
||
static func resizedImage(named name: String, fallbackSystemName: String, size: CGSize) -> UIImage? {
|
||
guard let source = image(named: name, fallbackSystemName: fallbackSystemName) else { return nil }
|
||
let renderer = UIGraphicsImageRenderer(size: size)
|
||
return renderer.image { _ in
|
||
source.draw(in: CGRect(origin: .zero, size: size))
|
||
}.withRenderingMode(.alwaysOriginal)
|
||
}
|
||
}
|