我是iOS开发的新手,我想知道是否可以下载多个图像取决于json配置(也可以从Internet下载)。
我了解到,我需要使用:
URLSession(configuration: config, delegate: JsonSessionDelegate.shared, delegateQueue: nil)
但这是问题所在。我需要更新我的应用程序,例如每5个小时使用新配置和新图像。该配置是与每个映像相同的单独REST GET调用。
是否有可能在后台获取json并依靠json单独获取所有图像,将其保存到内存中,并在重新启动应用程序时显示它们?
这是我的代码,AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
return true
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let config = URLSessionConfiguration.background(withIdentifier: "background")
let session = URLSession(configuration: config, delegate: JsonSessionDelegate.shared, delegateQueue: nil)
let task = session.downloadTask(with: getJsonUrl())
task.resume()
}
JsonSessionDelegate.swift:
static var shared = JsonSessionDelegate()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let data = try? Data(contentsOf: location) else { return }
let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
for (_, id) in json! {
let config = URLSessionConfiguration.background(withIdentifier: "bg2 \(id)")
let session = URLSession(configuration: config, delegate: ImageDelegate.shared, delegateQueue: nil)
let task = session.downloadTask(with: getImageUrl(id: id))
task.resume()
}
}
最后是ImageDelegate:
static var shared = ImageDelegate()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let data = try? Data(contentsOf: location)
...
if allImagesLoaded() {
saveImages()
}
}