mas/mas-cli/AppStore/Downloader.swift

60 lines
1.6 KiB
Swift
Raw Normal View History

//
// Downloader.swift
// mas-cli
//
// Created by Andrew Naylor on 21/08/2015.
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
//
2016-09-17 12:58:38 +00:00
func download(_ adamId: UInt64) -> MASError? {
2016-02-14 01:24:30 +00:00
guard let account = ISStoreAccount.primaryAccount else {
2016-09-25 21:13:23 +00:00
return .notSignedIn
2016-02-14 01:24:30 +00:00
}
2016-09-17 12:58:38 +00:00
let group = DispatchGroup()
2016-02-14 01:24:30 +00:00
let purchase = SSPurchase(adamId: adamId, account: account)
var purchaseError: MASError?
2016-09-17 12:58:38 +00:00
var observerIdentifier: Any? = nil
2016-02-14 01:24:30 +00:00
2016-09-17 12:58:38 +00:00
group.enter()
purchase.perform { purchase, _, error, response in
2016-02-14 01:24:30 +00:00
if let error = error {
2016-09-25 21:13:23 +00:00
purchaseError = .purchaseFailed(error: error as NSError?)
2016-09-17 12:58:38 +00:00
group.leave()
2016-02-14 01:24:30 +00:00
return
}
2015-08-24 18:45:54 +00:00
2016-09-17 12:58:38 +00:00
if let downloads = response?.downloads, downloads.count > 0, let purchase = purchase {
2016-02-14 01:24:30 +00:00
let observer = PurchaseDownloadObserver(purchase: purchase)
2016-02-14 01:24:30 +00:00
observer.errorHandler = { error in
purchaseError = error
2016-09-17 12:58:38 +00:00
group.leave()
}
2016-02-14 01:24:30 +00:00
observer.completionHandler = {
2016-09-17 12:58:38 +00:00
group.leave()
2015-08-24 18:45:54 +00:00
}
2016-09-17 12:58:38 +00:00
let downloadQueue = CKDownloadQueue.shared()
observerIdentifier = downloadQueue?.add(observer) as Any?
2016-02-14 01:24:30 +00:00
}
else {
print("No downloads")
2016-09-25 21:13:23 +00:00
purchaseError = .noDownloads
2016-09-17 12:58:38 +00:00
group.leave()
2015-08-24 18:45:54 +00:00
}
}
2016-02-14 01:24:30 +00:00
2016-09-17 12:58:38 +00:00
let _ = group.wait(timeout: DispatchTime.distantFuture)
if let observerIdentifier = observerIdentifier {
2016-09-17 12:58:38 +00:00
CKDownloadQueue.shared().removeObserver(observerIdentifier)
}
2016-02-14 01:24:30 +00:00
return purchaseError
2015-08-24 18:45:54 +00:00
}