Commit d53fccf7 authored by Philip Brechler's avatar Philip Brechler

Download eggs to file system and inform delegate

parent ccdb1a85
......@@ -11,6 +11,8 @@ import SWCompression
protocol HatcheryClientDelegate: class {
func didRefreshListOfEggs()
func didDownloadEggToPath(_ path: URL)
func didFailToDownloadEgg()
}
class HatcheryClient: NSObject, URLSessionDelegate {
......@@ -127,17 +129,38 @@ class HatcheryClient: NSObject, URLSessionDelegate {
private func unpackEgg(_ localFile: URL) {
let data = try? Data.init(contentsOf: localFile)
let unpackUrl = FileManager.default.temporaryDirectory
let unpackUrl = FileManager.default.temporaryDirectory.appendingPathComponent("downloaded_eggs")
do {
let decompressedTarData = try GzipArchive.unarchive(archive: data!)
let unpackedTar = try TarContainer.open(container: decompressedTarData)
var createdFileCount: Int = 0
var folderNameForEgg: String?
for tarEntry in unpackedTar {
let fileName = unpackUrl.appendingPathComponent(tarEntry.info.name)
let data = tarEntry.data
//TODO: Upload files to card10 or safe?
if folderNameForEgg == nil {
folderNameForEgg = fileName.deletingLastPathComponent().path // Kind of betting on that there are no subfolders
}
try FileManager.default.createDirectory(at: fileName.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
if (FileManager.default.createFile(atPath: fileName.path, contents: data, attributes: nil)) {
createdFileCount += 1 //Increment so we know if we wrote all the files
} else {
print("Failed to write file to path ",fileName)
}
}
if createdFileCount == unpackedTar.count {
//Success, we downloaded and stored all the files
delegate?.didDownloadEggToPath(URL(string: folderNameForEgg!) ?? unpackUrl)
} else {
delegate?.didFailToDownloadEgg()
}
} catch let error {
print(error)
delegate?.didFailToDownloadEgg()
}
}
......
......@@ -44,7 +44,16 @@ class HatcheryDetailViewController: UIViewController,HatcheryClientDelegate {
func didRefreshListOfEggs() {}
func didDownloadEggToPath(_ path: URL) {
//TODO: Call BluetoothManager to upload? Just tell the user and they do it Control?
}
func didFailToDownloadEgg() {
let failedAlert = UIAlertController(title: "Error", message: "Failed to download egg", preferredStyle: .alert)
failedAlert.addAction(UIAlertAction.init(title: "OK", style: .default, handler: nil))
self.present(failedAlert, animated: true)
}
}
......@@ -77,5 +77,9 @@ class HatcheryRootTableViewController: UITableViewController,HatcheryClientDeleg
@IBAction func refreshEggs(sender:UIRefreshControl) {
self.client?.updateListOfHatcheryEggs()
}
func didDownloadEggToPath(_ path: URL) {}
func didFailToDownloadEgg() {}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment