ios - 在 Swift 中从字符串创建 ZIP 文件

标签 ios swift zip nsfilemanager ssziparchive

 let data = "InPractiseThisWillBeAReheallyLongString"
     
        createDir()
        
        let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let ourDir = docsDir.appendingPathComponent("ourCustomDir/")
        let tempDir = ourDir.appendingPathComponent("temp/")
        let unzippedDir = tempDir.appendingPathComponent("unzippedDir/")
        let unzippedfileDir = unzippedDir.appendingPathComponent("unZipped.txt")
        let zippedDir = tempDir.appendingPathComponent("Zipped.zip")
        do {
            
            try data.write(to: unzippedfileDir, atomically: false, encoding: .utf8)
            
            
            let x = SSZipArchive.createZipFile(atPath: zippedDir.path, withContentsOfDirectory: unzippedfileDir.path)
            
            var zipData: NSData! = NSData()
            
            do {
                zipData = try NSData(contentsOfFile: unzippedfileDir.path, options: NSData.ReadingOptions.mappedIfSafe)
                //once I get a readable .zip file, I will be using this zipData in a multipart webservice
            }
            catch let err as NSError {
                print("err 1 here is :\(err.localizedDescription)")
            }
        }
        catch let err as NSError {
            
            print("err 3 here is :\(err.localizedDescription)")
        }

createDir 函数是:

func createDir() {
        let docsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let ourDir = docsDir.appendingPathComponent("ourCustomDir/")
        let tempDir = ourDir.appendingPathComponent("temp/")
        let unzippedDir = tempDir.appendingPathComponent("unzippedDir/")
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: tempDir.path) {
            deleteFile(path: tempDir)
            deleteFile(path: unzippedDir)
        } else {
            print("file does not exist")
            do {
                try FileManager.default.createDirectory(atPath: tempDir.path, withIntermediateDirectories: true, attributes: nil)
                try FileManager.default.createDirectory(atPath: unzippedDir.path, withIntermediateDirectories: true, attributes: nil)
                print("creating dir \(tempDir)")
            } catch let error as NSError {
                print("here : " + error.localizedDescription)
            }
        }
    }

现在我没有收到任何错误,但是当我下载我的 appData 容器、获取 ZIP 文件并尝试解压缩时,我可能会告诉我 ZIP 文件是空的。我可以看到 unzipped.text 文件确实按预期存在。

知道我做错了什么吗?

有没有一种方法可以直接从字符串创建一个.zip,而不必将文件保存到数据容器中?


更新

我也尝试了以下并得到了完全相同的结果:

let zipArch = SSZipArchive(path: zippedDir.path)
        print(zipArch.open)
        print(zipArch.write(dataStr.data(using: String.Encoding.utf8)!, filename: "blah.txt", withPassword: ""))
        print(zipArch.close)

最佳答案

我是用 ZipFoundation 做的 --> https://github.com/weichsel/ZIPFoundation

swift

100% 工作!!

1) 将 ZipFoundation Framework 添加到您的项目中

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 */}
    }
}

我的控制台输出...

已创建

已添加

提取

我喜欢压缩文件

关于ios - 在 Swift 中从字符串创建 ZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46814128/

相关文章:

javascript - 在 iOS 模拟器上运行 React-Native 应用程序

swift - Cocoa Touch 框架的核心数据

ios - UIView TouchsBegan 未被调用

ios - 从 UIActivityViewController 中的 API 获取的自定义消息

ios - 如何更改 UISearchBar 中 UITextField 的属性

ios - 将 Facebook 应用链接链接到 iTunes 下载页面

ios - 更改导航 Controller 项目颜色

Java.util.zip 添加新文件会覆盖整个 jar 吗?

c# - 在 Linux 上使用 .net core 创建的 Zip 文件缺少读取权限

PowerShell脚本没有压缩正确的文件