unzipping a file in cocoa

后端 未结 7 1150
长发绾君心
长发绾君心 2020-12-18 01:59

I have a zipped file, which i want to extract the contents of it. What is the exact procedure that i should do to achieve it. Is there any framework to unzip the files in co

7条回答
  •  遥遥无期
    2020-12-18 02:18

    Here's a Swift 4 version similar to Sven Driemecker's answer.

    func unzipFile(at sourcePath: String, to destinationPath: String) -> Bool {
        let process = Process.launchedProcess(launchPath: "/usr/bin/unzip", arguments: ["-o", sourcePath, "-d", destinationPath])
        process.waitUntilExit()
        return process.terminationStatus <= 1
    }
    

    This implementation returns a boolean that determines if the process was successful or not. Is considering the process successful even if warnings were encountered.

    The return condition can be changed to return process.terminationStatus == 0 to not even accept warnings.

    See unzip docs for more details on diagnostics.

    You can also capture the output of the process using a Pipe instance.

    func unzipFile(at sourcePath: String, to destinationPath: String) -> Bool {
        let process = Process()
        let pipe = Pipe()
    
        process.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")
        process.arguments = ["-o", sourcePath, "-d", destinationPath]
        process.standardOutput = pipe
    
        do {
            try process.run()
        } catch {
            return false
        }
    
        let resultData = pipe.fileHandleForReading.readDataToEndOfFile()
        let result = String (data: resultData, encoding: .utf8) ?? ""
        print(result)
    
        return process.terminationStatus <= 1
    }
    

提交回复
热议问题