My Problem
How do I return a cgImage from QLThumbnailGenerator.shared.generateRepresentations(for: ... )?
My Hangups/Attempt (Code Below)
My attempt has a function (line 13) that returns a CGImage for a ListView entry (line 39). I tried to use an empty CGImage (line 18), but its init parameters are confusing and seem excessive for a simple thumbnail. I'm likely going about this incorrectly.
Notes
- CGImage is used so the same code can work for both iOS and MacOS Catalyst. (Saw this in WWDC 2019 session 719.)
- I tried but failed to glean an answer from:
- App overview: This is a public service app that searches a specified library of PDFs for an array of terms for misidentified biomaterials, helping biologists screen for potentially false results in every paper they've read. It will be free.
Apology/Gratitude:
Thanks for your patience, as the answer is likely obvious and my vocabulary likely off. My dumb brain tunes out lectures without a little hands-on experience, so I started this first app from zero programming knowledge as a quarantine hobby. I'll return to the theory lectures after.
Code: ResultsView.swift
import SwiftUI
import MobileCoreServices
import Combine
import QuickLookThumbnailing
import CoreImage
import UIKit
struct ResultsView: View {
@EnvironmentObject var parsedScreeningData: ParsedScreeningData
@EnvironmentObject var search: Search
func generateThumbnail(ofThis: String) -> CGImage {
let url = self.search.libraryFolder.appendingPathComponent(ofThis)
let size: CGSize = CGSize(width: 68, height: 88)
let request = QLThumbnailGenerator.Request(fileAt: url, size: size, scale: (UIScreen.main.scale), representationTypes: .all)
let generator = QLThumbnailGenerator.shared
var image = CGImage()
generator.generateRepresentations(for: request) { (thumbnail, type, error) in
DispatchQueue.main.async {
if thumbnail == nil || error != nil {
assert(false, "Thumbnail failed to generate")
} else {
image = thumbnail!.cgImage
}
}
}
return image
}
var body: some View {
VStack{
List(search.searchResults) { datum in
HStack {
Image(self.generateThumbnail(ofThis: datum.PDFname), scale: (UIScreen.main.scale), label: Text("PDF"))
Text("File: \(datum.PDFname)")
Text("Cell line: \(self.parsedScreeningData.parsedScreeningData[datum.termFoundIndex].misidentifiedCellLine)")
.padding(.trailing, 10)
.padding(.leading, 10)
Spacer()
Image(systemName: "eyeglasses").foregroundColor(ColorManager.iconGreen)
// .onTapGesture {
// let url = URL.init(string: "\(datum.termFoundIndex)")
// guard let thisAddress = url, UIApplication.shared.canOpenURL(thisAddress) else { return }
// UIApplication.shared.open(thisAddress)
} // HStack
} // List
}// Vstack
.colorMultiply(ColorManager.beigeMedium)
.padding(.trailing, 0)
.padding(.leading, 0)
.listStyle(GroupedListStyle())
} // body
} // ResultsView struct
struct ResultsView_Previews: PreviewProvider {
static var previews: some View {
ResultsView().environmentObject(ParsedScreeningData()).environmentObject(Search())
}
}