-
-
Save gngrwzrd/01168cf44567ce6fc573c539baf57bb8 to your computer and use it in GitHub Desktop.
CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension URL { | |
static var documentsDirectory:URL { | |
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) | |
let documentsDirectory = paths[0] | |
let path = documentsDirectory as String | |
return URL(fileURLWithPath: path, isDirectory: true) | |
} | |
} | |
class ThankyouCSVDownloader { | |
var fileSaveURL:URL { | |
let dateString = DateUtil.shared.serverDateFromDate(date: .now) | |
let fileName = dateString + "-" + "gift-tracker.csv" | |
return URL.documentsDirectory.appendingPathComponent(fileName) | |
} | |
func downloadAndSave(client:BLAPIClient = .sharedInstance(), completion:@escaping (Error?)->Void) { | |
client.getPath("../../registry/gift-tracker.csv", parameters: nil, successWithData: { data in | |
DispatchQueue.global(qos: .userInitiated).async2 { [self] in | |
do { | |
try data.write(to: fileSaveURL, options: [.atomic, .completeFileProtection]) | |
DispatchQueue.main.async2 { | |
completion(nil) | |
} | |
} catch { | |
DispatchQueue.main.async2 { | |
completion(error) | |
} | |
} | |
} | |
}, failure: { error in | |
completion(error) | |
}) | |
} | |
func downloadAndSaveAsync(client:BLAPIClient = .sharedInstance()) async -> Error? { | |
let result = await client.asyncGet(path: "../../registry/gift-tracker.csv") | |
switch result { | |
case .success(let data): | |
do { | |
try data.write(to: fileSaveURL, options: [.atomic, .completeFileProtection]) | |
} catch { | |
return error | |
} | |
case .failure(let error): | |
return error | |
} | |
return nil | |
} | |
} | |
class GiftReservationsV2 : ... { | |
//... | |
func showDownloadThankYouList_async() { | |
let downloader = ThankyouCSVDownloader() | |
SVProgressHUD.show() | |
Task { | |
let error = await downloader.downloadAndSaveAsync() | |
await MainActor.run { //could use dispatch too | |
SVProgressHUD.dismiss() | |
if let error { | |
showAPIError(error) | |
return | |
} | |
self.showActivityView(downloader.fileSaveURL) | |
} | |
} | |
} | |
func showDownloadThankyouList_block() { | |
//IMO this is cleaner. Take the thread concerns out of the VC, let the abstraction callback on main. | |
let downloader = ThankyouCSVDownloader() | |
SVProgressHUD.show() | |
downloader.downloadAndSave { error in | |
SVProgressHUD.dismiss() | |
if let error { | |
self.showAPIError(error) | |
return | |
} | |
showActivityView(downloader.fileSaveURL) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment