我用 ZipFoundation 做到了 -->https://github.com/weichsel/ZIPFoundation https://github.com/weichsel/ZIPFoundation
SWIFT
100% 工作!!
1) 将 ZipFoundation 框架添加到您的项目中
2) 添加导入到你的类中
import ZIPFoundation //Add to top of your class
通话功能
zipString() . // Do your work
extract(fileName: "myZip.zip") //Extract it to test it
read(fileName : "zipTxt.txt" ) //Read you extracted File
为你的类添加函数
func zipString() {
let zipName = "myZip.zip"
let myTxtName = "zipTxt.txt"
let myString = "I love to zip files" // In your case "InPractiseThisWillBeAReheallyLongString"
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(zipName)
//Create the zip file
guard let archive = Archive(url: fileURL, accessMode: .create) else {
return
}
/* guard let archive = Archive(url: fileURL, accessMode: .update) else {
return
} */ // In case you want to update
print("CREATED")
//Add file to
let data = myString.data(using: .utf8)
try? archive.addEntry(with: myTxtName, type: .file, uncompressedSize: UInt32(data!.count), compressionMethod: .deflate, provider: { (position, size) -> Data in
return data!
})
print("ADDED")
}
}
奖励文件提取
/**
** Extract file for a given name
**/
func extract(fileName : String){
let fileManager = FileManager()
let file = fileName
// let currentWorkingPath = fileManager.currentDirectoryPath
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
do {
// try fileManager.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
try fileManager.unzipItem(at: fileURL, to: dir)
print("EXTRACTED")
} catch {
print("Extraction of ZIP archive failed with error:\(error)")
}
}
}
用于测试提取的文件
func read(fileName : String){
let file = fileName //this is the file. we will write to and read from it
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
print(text2)
}
catch {/* error handling here */}
}
}
我的控制台输出...
CREATED
ADDED
提取
我喜欢压缩文件