2020-07-11 11:01:09 +02:00
|
|
|
//
|
|
|
|
// WidgetDataEncoder.swift
|
|
|
|
// Multiplatform iOS
|
|
|
|
//
|
|
|
|
// Created by Stuart Breckenridge on 11/7/20.
|
|
|
|
// Copyright © 2020 Ranchero Software. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import WidgetKit
|
|
|
|
import os.log
|
2020-07-11 15:02:46 +02:00
|
|
|
import UIKit
|
2020-07-11 11:01:09 +02:00
|
|
|
|
|
|
|
struct WidgetDataEncoder {
|
|
|
|
|
2020-07-11 15:02:46 +02:00
|
|
|
static let taskIdentifier = "com.ranchero.NetNewsWire.WidgetEncode"
|
|
|
|
|
2020-07-11 11:01:09 +02:00
|
|
|
static func encodeWidgetData() {
|
2020-07-11 14:22:21 +02:00
|
|
|
os_log(.info, "Starting widget data encoding")
|
2020-07-11 15:02:46 +02:00
|
|
|
let task = UIApplication.shared.beginBackgroundTask(withName: taskIdentifier, expirationHandler: nil)
|
2020-07-11 11:01:09 +02:00
|
|
|
do {
|
|
|
|
let articles = try SmartFeedsController.shared.unreadFeed.fetchArticles().sorted(by: { $0.datePublished! > $1.datePublished! })
|
|
|
|
var latest = [LatestArticle]()
|
|
|
|
for article in articles {
|
|
|
|
let latestArticle = LatestArticle(feedTitle: article.sortableName,
|
|
|
|
articleTitle: article.title,
|
|
|
|
articleSummary: article.summary,
|
|
|
|
feedIcon: article.iconImage()?.image.dataRepresentation(),
|
|
|
|
pubDate: article.datePublished!.description)
|
|
|
|
latest.append(latestArticle)
|
|
|
|
if latest.count == 5 { break }
|
|
|
|
}
|
|
|
|
|
|
|
|
let latestData = WidgetData(currentUnreadCount: SmartFeedsController.shared.unreadFeed.unreadCount,
|
|
|
|
currentTodayCount: SmartFeedsController.shared.todayFeed.unreadCount,
|
|
|
|
latestArticles: latest,
|
|
|
|
lastUpdateTime: Date())
|
|
|
|
|
|
|
|
let encodedData = try JSONEncoder().encode(latestData)
|
|
|
|
let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String
|
|
|
|
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)
|
|
|
|
let dataURL = containerURL?.appendingPathComponent("widget-data.json")
|
|
|
|
if FileManager.default.fileExists(atPath: dataURL!.path) {
|
|
|
|
try FileManager.default.removeItem(at: dataURL!)
|
|
|
|
}
|
|
|
|
try encodedData.write(to: dataURL!)
|
|
|
|
|
|
|
|
WidgetCenter.shared.reloadAllTimelines()
|
2020-07-11 14:22:21 +02:00
|
|
|
os_log(.info, "Finished encoding widget data")
|
2020-07-11 15:02:46 +02:00
|
|
|
print(UIApplication.shared.backgroundTimeRemaining)
|
|
|
|
UIApplication.shared.endBackgroundTask(task)
|
2020-07-11 11:01:09 +02:00
|
|
|
} catch {
|
|
|
|
os_log(.error, "%@", error.localizedDescription)
|
2020-07-11 15:02:46 +02:00
|
|
|
UIApplication.shared.endBackgroundTask(task)
|
2020-07-11 11:01:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|