Reputation:
I'm trying to add a file to an archive in Swift using the ZIPFoundation lib.
The archive looks like this:
/
/folder1/
/folder2/ <-- Move file here.
Currently using this to add my file to the archive, but I don't get the logic of the parameters:
public func addEntry(with path: String, relativeTo baseURL: URL)
Creating an Archive
object and adding the file using addEntry()
, is there a way to not just add the file to the root path of the archive?
Code Edit:
internal func moveLicense(from licenseUrl: URL, to publicationUrl: URL) throws {
guard let archive = Archive(url: publicationUrl, accessMode: .update) else {
return
}
// Create local folder to have the same path as in the archive.
let fileManager = FileManager.default
var urlMetaInf = licenseUrl.deletingLastPathComponent()
urlMetaInf.appendPathComponent("META-INF", isDirectory: true)
try fileManager.createDirectory(at: urlMetaInf, withIntermediateDirectories: true, attributes: nil)
let uuu = URL(fileURLWithPath: urlMetaInf.path, isDirectory: true)
// move license in the meta-inf folder.
try fileManager.moveItem(at: licenseUrl, to: uuu.appendingPathComponent("license.lcpl"))
// move dir
print(uuu.lastPathComponent.appending("/license.lcpl"))
print(uuu.deletingLastPathComponent())
do {
try archive.addEntry(with: uuu.lastPathComponent.appending("license.lcpl"), // Missing '/' before license
relativeTo: uuu.deletingLastPathComponent())
} catch {
print(error)
}
}
// This is still testing code, don't mind the names :)
Upvotes: 1
Views: 1511
Reputation: 34253
Path entries in ZIP archives are not really hierarchical paths like on most modern file systems. They are more or less just identifiers. Usually those identifiers are used to store the path that pointed to the entry on the origin file system.
The addEntry(with path: ...)
method in ZIPFoundation is just a convenience method for the above use case.
For example, let's say we want to add an entry from a file that has the following path on a physical file system:
/temp/x/fileA.txt
If we want to use a relative path to identify the fileA.txt
entry within the archive, we could use:
archive.addEntry(with: "x/fileA.txt", relativeTo: URL(fileURLWithPath: "/temp/")
Later, this would allow us to look up the entry with:
archive["x/fileA.txt"]
If we don't want to keep any path information except the filename, we could use:
let url = URL(fileURLWithPath: "/temp/x/fileA.txt"
archive.addEntry(with: url.lastPathComponent, relativeTo: url.deletingLastPathComponent())
This would allow us to look up the entry just using the filename:
archive["fileA.txt"]
If you need more control over the path/filename, you can use the closure based API in ZIPFoundation. This is especially useful if your entry contents come from memory or you want to add entries from files that don't have a common parent directory.
Upvotes: 3