Skip to content

Instantly share code, notes, and snippets.

@gustafnilklint
Last active August 12, 2020 00:03
Show Gist options
  • Save gustafnilklint/b4aa0709ee4b51fe76ecabe29ec34100 to your computer and use it in GitHub Desktop.
Save gustafnilklint/b4aa0709ee4b51fe76ecabe29ec34100 to your computer and use it in GitHub Desktop.
BackgroundRefresh
//
// BackgroundService.swift
//
// Created by Gustaf on 2020-01-27.
// Copyright © 2020 Gustaf. All rights reserved.
//
import Foundation
import WatchKit
class BackgroundService: NSObject {
static let shared = BackgroundService()
static let url = URL(string: "api-url")!
// Store tasks in order to complete them when finished
var pendingBackgroundTasks = [WKURLSessionRefreshBackgroundTask]()
func updateContent() {
let configuration = URLSessionConfiguration
.background(withIdentifier: "myBgTaskID")
let session = URLSession(configuration: configuration,
delegate: self, delegateQueue: nil)
let backgroundTask = session.downloadTask(with: url)
backgroundTask.resume()
}
func handleDownload(_ backgroundTask: WKURLSessionRefreshBackgroundTask) {
let configuration = URLSessionConfiguration
.background(withIdentifier: backgroundTask.sessionIdentifier)
let _ = URLSession(configuration: configuration,
delegate: self, delegateQueue: nil)
pendingBackgroundTasks.append(backgroundTask)
}
}
extension BackgroundService : URLSessionDownloadDelegate {
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
processFile(file: location)
self.pendingBackgroundTasks.forEach {
$0.setTaskCompletedWithSnapshot(false)
}
}
func processFile(file: URL){
if let data = try? Data(contentsOf: file),
let model = try? JSONDecoder()
.decode(ModelObject.self, from: data) {
// persist or handle your data
print("Success")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment