LoginSignup
0
1

More than 1 year has passed since last update.

Swiftで複数ファイルを纏めて圧縮..圧縮ぅ!!

Posted at

事のきっかけ

GUI的には直ぐにできる操作だけども、Swift的にどうすれば良いのか気になった次第。

使用技術

  • Zip Foundation: Swiftネイティブで圧縮するライブラリ。
  • Swift: プログラミング言語

開発環境

  • macOS Big Sur Intel Mac
  • Xcode 13.1

内容

フォルダ構成

Documentフォルダにworkフォルダを作成して保存

[Document]
|-[work]
    |- test.png
    |- test.txt
    |- test.yaml

手順(上から順に)

  • 参考サイトを参考にZipFoundationのパッケージをインポート

  • main.swiftに下記を記載して実行。

main.swift
import Foundation
import ZIPFoundation

func archiveFile() throws -> Void {
  // fileManager
  let fileManager = FileManager()

  // User Document Folder
  let path: URL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
  let workingPath: URL = path.appendingPathComponent("work", isDirectory: true)
  print("====WORKING-PATH=====")
  print(workingPath)
  print("=====================")

  // get Working Contents
  guard let workingContents: [String] = try? fileManager.contentsOfDirectory(atPath: workingPath.path) else {return}

  // filter .DS_Store
  let filteredworkingContents: [String] = workingContents.filter{$0 != ".DS_Store"}
  let sourceURLs: [URL] = filteredworkingContents.map{workingPath.appendingPathComponent($0, isDirectory: false)}
  print("====SOURCE-URLS======")
  print(sourceURLs)
  print("=====================")

  // create tmp folder
  do {
    try fileManager.createDirectory(at: workingPath.appendingPathComponent("tmp", isDirectory: true), withIntermediateDirectories: false, attributes: nil)
  } catch {
    print("ERROR")
  }

  let archiveURL = workingPath.appendingPathComponent("tmp/test.zip", isDirectory: false)
  print("=====ARCHIVE-URL=====")
  print(archiveURL)
  print("=====================")
  guard let archive = Archive(url: archiveURL, accessMode: .create) else {
    throw Archive.ArchiveError.unwritableArchive
  }
  do {
    try sourceURLs.forEach{
      try archive.addEntry(with: $0.lastPathComponent, relativeTo: $0.deletingLastPathComponent())
    }
  } catch {
    print("Error")
  }

}

try archiveFile()

ここに至るまで。

特定のファイルをZip化したいと思い、やり方を調べていたが、ZipFoundationの公式サイトを見ても書いておらず、日本語のサイトや英語のサイトを探索したが全くと言っていいほど情報がなかった。
しかし、公式サイトにはディレクトリを指定する事で纏めてZip化しているサンプルコードがあったため、このサンプルコードをよすがにコードをたどる事で見つけることができた。

まとめ

ドキュメントだけでなく、利用するライブラリのコードを直接見ることで、事細かにカスタマイズできることを改めて認知した。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1