Slide 23
Slide 23 text
final class BackgroundFetcher: NSObject, URLSessionDownloadDelegate {
static let shared = BackgroundFetcher()
var completion: (() -> Void)?
private lazy var session: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "get_huge_data")
config.isDiscretionary = true // ిݯଓதWiFiଓதͳͲͷྑ͍λΠϛϯάͰDL
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
func restoreURLSessionIfNeeded() {
_ = session
}
// getTimeline͔Βݺͼग़͢
func setDownloadSchedule(completion: (() -> Void)? = nil) {
session.getTasksWithCompletionHandler { _, _, downloadTasks in
defer { completion?() }
guard downloadTasks.isEmpty else { return }
let task = Self.shared.session.downloadTask(with: URL(string: "https://****")!)
task.earliestBeginDate = <࣍ͷϦϩʔυλΠϛϯάΑΓલʹઃఆ>
task.countOfBytesClientExpectsToSend = 500
task.countOfBytesClientExpectsToReceive = 8 * 1024 * 1024
task.resume()
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// DLͨ͠σʔλΛDocumentsσΟϨΫτϦͳͲʹҠಈͯ͠ޙ͔ΒऔಘͰ͖ΔΑ͏ʹ͢Δ
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
completion?()
completion = nil
WidgetCenter.shared.reloadTimelines(ofKind: "CatWidget")
}
}
ɾσʔλΛࣄલDL͢ΔͱಡΈࠐΈͪΛݮͰ͖Δ
ɾϦτϥΠॲཧͰΑΓ࣮֬ʹϑΣονͰ͖Δ