Swift - Zip Files from directory without creating a directory inside zip directory

Viewed 387

I'm working with Swift 5.0 and I want to zip 3 files without installing additional dependencies.

Currently I'm able to zip these 3 Files, which all are in the same "root" directory. But if I open the created and exported zip-file (final.zip), than I get the folder (root) in which the 3 files were saved. I don't want this "root" folder. I want to see my data directly inside the final.zip

Below is my code. Can someone help me out?

let fm = FileManager.default

let baseDirectoryUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("root", isDirectory: true)

if !manager.fileExists(atPath: baseDirectoryUrl.relativePath) {
    try! manager.createDirectory(
        at: baseDirectoryUrl,
        withIntermediateDirectories: true,
        attributes: nil
    )
}

// path of data
let data1_path = baseDirectoryUrl.appendingPathComponent("data1.vec3")
let data2_path = baseDirectoryUrl.appendingPathComponent("data2.vec3")
let data3_path = baseDirectoryUrl.appendingPathComponent("data3.json")

// write wData1 to data1_path
try! wData1.write(to: data1_path)

// write wData2 to data2_path
try! wData2.write(to: data2_path)

// write wData3 to data3_path
try! wData3.write(to: data3_path)


// this will hold the URL of the zip file
var archiveUrl: URL?
// if we encounter an error, store it here
var error: NSError?

let coordinator = NSFileCoordinator()
// zip up the root directory
// this method is synchronous and the block will be executed before it returns
// if the method fails, the block will not be executed though
// if you expect the archiving process to take long, execute it on another queue

coordinator.coordinate(readingItemAt: baseDirectoryUrl, options: [.forUploading], error: &error) { (zipUrl) in
    // zipUrl points to the zip file created by the coordinator
    // zipUrl is valid only until the end of this block, so we move the file to a temporary folder
    let tmpUrl = try! fm.url(
        for: .itemReplacementDirectory,
        in: .userDomainMask,
        appropriateFor: zipUrl,
        create: true
    ).appendingPathComponent("export.zip", isDirectory: false)
    try! fm.copyItem(at: zipUrl, to: tmpUrl)

    // store the URL so we can use it outside the block
    archiveUrl = tmpUrl
}


if let archiveUrl = archiveUrl {
    // bring up the share sheet so we can send the archive with AirDrop for example
    let avc = UIActivityViewController(activityItems: [archiveUrl], applicationActivities: nil)
    avc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
    present(avc, animated: true)
} else {
    print(error)
}
1 Answers
Related