Swift进行zip\unzip加解密之SSZipArchive、GoogleUtilities
参考:
使用NSData+zlib
进行zip、unzip操作
zip的压缩与解压缩
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Foundation
import GoogleUtilities
extension Data {
var gzip: Data? {
do {
let result = try NSData.gul_data(byGzippingData: self)
return result
} catch let error {
print(error)
}
return nil
}
var gUnZip: Data? {
do {
let result = try NSData.gul_data(byInflatingGzippedData: self)
return result
} catch let error {
print(error)
}
return nil
}
}
使用SSZipArchive
进行压缩解压缩
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func testZipFile() {
// 压缩后的文件夹存放在的地址
let zipFile = PathTool.temporaryDir.appendPath("a/log.zip")
// 创建压缩后生成的zip文件所在的文件夹
PathTool.createDir(path: zipFile.dirPath)
// 要压缩的的源文件所在的文件夹
let dir = PathTool.cacheDir.appendPath("/mylog/")
// 将文件夹dir进行zip压缩,并以123456进行加密
let result = SSZipArchive.createZipFile(atPath: zipFile, withContentsOfDirectory: dir, withPassword: "123456")
print("result: \(result ? "true" : "false")")
}
func testUnZipFile() {
// 压缩后的文件夹存放在的地址
let zipFile = PathTool.temporaryDir.appendPath("a/log.zip")
let toFile = PathTool.temporaryDir.appendPath("a/b")
do {
try? SSZipArchive.unzipFile(atPath: zipFile, toDestination: toFile, overwrite: true, password: "123456")
//print("result: \(result ? "true" : "false")")
} catch {
print(error)
}
}
path的工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import Foundation
import CoreServices
public class PathTool {
private init() {}
public class func isDir(path: String) -> Bool {
var isDirectory: ObjCBool = false
FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return isDirectory.boolValue ? true : false
}
public class func exists(path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
@discardableResult
public class func createDir(path: String) -> Bool {
if exists(path: path) == false {
return ((try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)) != nil)
}
return true
}
@discardableResult
public class func createDirIfNotExist(path: String) -> Bool {
if exists(path: path) == false {
return ((try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)) != nil)
}
return true
}
@discardableResult
public class func remove(_ path: String) -> Bool {
var rtn = true
do {
try FileManager.default.removeItem(atPath: path)
} catch {
rtn = false
print(error)
}
return rtn
}
@discardableResult
public class func copy(path: String, toPath: String) -> Bool {
return ((try? FileManager.default.copyItem(atPath: path, toPath: toPath)) != nil)
}
@discardableResult
public class func move(path: String, toPath: String) -> Bool {
return ((try? FileManager.default.moveItem(atPath: path, toPath: toPath)) != nil)
}
public class func updateModificationDate(path: String, date: Date = Date()) -> Bool {
return ((try? FileManager.default.setAttributes([FileAttributeKey.modificationDate: date], ofItemAtPath: path)) != nil)
}
public class func read(path: String) -> String? {
return try? String(contentsOfFile: path, encoding: .utf8)
}
@discardableResult
public class func write(path: String, text: String) -> Bool {
createDirIfNotExist(path: path.dirPath)
return (((try? text.write(toFile: path, atomically: true, encoding: .utf8)) != nil))
}
@discardableResult
public class func readData(path: String) -> Data? {
return FileManager.default.contents(atPath: path)
}
@discardableResult
public class func writeData(path: String, data: Data) -> Bool {
return FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
}
@discardableResult
public class func makeDir(path: String) -> Bool {
return ((try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)) != nil)
}
// 删除文件夹下的所有文件
public static func deleteFolder(_ folderPath: String){
if isDir(path: folderPath) {
if let subFilePathList = FileManager.default.subpaths(atPath: folderPath) {
DispatchQueue.global().async {
for path in subFilePathList {
let fileAbsoluePath = folderPath + "/" + path
remove(fileAbsoluePath)
}
}
}
}
}
// 遍历所有子目录 并计算文件大小
public static func forderSizeByDocumentPath(_ forderPath: String) -> CGFloat {
var fileSize: CGFloat = 0
if isDir(path: forderPath) {
if let subFilePathList = FileManager.default.subpaths(atPath: forderPath) {
for path in subFilePathList {
let fileAbsoluePath = forderPath + "/" + path
fileSize += fileSizeAtPath(fileAbsoluePath)
}
}
}
return fileSize
}
// 计算单个文件的大小
public static func fileSizeAtPath(_ filePath: String?) -> CGFloat {
guard let filePath = filePath else {
return 0
}
var fileSize: CGFloat = 0.0
if exists(path: filePath) {
if let attr = try? FileManager.default.attributesOfItem(atPath: filePath), let size = attr[FileAttributeKey.size] as? CGFloat {
fileSize = size
}
}
return fileSize
}
public static func mimeType(withUTI UTI: String?) -> String {
guard let uti = UTI else {
return "application/octet-stream"
}
if let mimetype = UTTypeCopyPreferredTagWithClass(uti as CFString, kUTTagClassMIMEType)?
.takeRetainedValue() {
return mimetype as String
} else {
return "application/octet-stream"
}
}
public class var homeDir: String{
return NSHomeDirectory()
}
public class var temporaryDir: String {
return NSTemporaryDirectory()
}
public class var documentsDir: String {
return userDomainOf(pathEnum: .documentDirectory)
}
public class var libraryDir: String {
return userDomainOf(pathEnum: .libraryDirectory)
}
public class var cacheDir: String {
return userDomainOf(pathEnum: .cachesDirectory)
}
private class func userDomainOf(pathEnum: FileManager.SearchPathDirectory) -> String {
return NSSearchPathForDirectoriesInDomains(pathEnum, .userDomainMask, true)[0]
}
public class var documentsDirUrl: URL {
return userDomainUrlOf(pathEnum: .documentDirectory)
}
public class var cacheDirUrl: URL {
return userDomainUrlOf(pathEnum: .cachesDirectory)
}
private class func userDomainUrlOf(pathEnum: FileManager.SearchPathDirectory) -> URL {
return FileManager.default.urls(for: pathEnum, in: .userDomainMask)[0]
}
static var totalDiskSpaceInBytes: Int64 {
guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value else { return 0 }
return space
}
static var freeDiskSpaceInBytes: Int64 {
if #available(iOS 11.0, *) {
if let space = try? URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage {
return space
} else {
return 0
}
} else {
if let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value {
return freeSpace
} else {
return 0
}
}
}
}
// MARK: - 文件相关
extension String {
var dirPath: String {
return (self as NSString).deletingLastPathComponent
}
var lastPath: String {
get {
return (self as NSString).lastPathComponent
}
}
func appendPath(_ path: String) -> String {
return (self as NSString).appendingPathComponent(path)
}
var pathExtension: String {
get {
return (self as NSString).pathExtension
}
}
var deletingPathExtension: String {
get {
return (self as NSString).deletingPathExtension
}
}
func appendingPathExtension(_ str: String) -> String {
if let newStr = (self as NSString).appendingPathExtension(str) {
return newStr
}
return self
}
}
This post is licensed under CC BY 4.0 by the author.