In my app I have an option to print delivery note. When I tap this option, I receive a response from server with a url (url of a PDF file). As soon as the response is received, the app navigate to a screen which contains a button to perform a printing action. Everything works ok until here. But when I tap the print button, the view gets frozen. I receive warning, that it is a synchronous url loading which causes app's ui unresponsive. It suggests to use some Asynchronous url loading like URLSession. But I have no idea how to use it in this case. Any help would be appreciated. I have provided code sample below.
public enum PrintingResult {
case success
case failure(Error)
case userCancelled
}
public func presentPrintInteractionController(url: URL?, jobName: String? = nil, completion: ((PrintingResult) -> Void)? = nil) {
let printController = UIPrintInteractionController()
let printInfo = UIPrintInfo.printInfo()
if let jobName = jobName {
printInfo.jobName = jobName
}
printController.printInfo = printInfo
if let url = url {
printController.printingItem = url
}
printController.present(animated: true) { _, completed, error in
guard let completion = completion else { return }
if completed {
completion(.success)
} else {
if let error = error {
completion(.failure(error))
} else {
completion(.userCancelled)
}
}
}
}
View:
import SwiftUI
struct ReportView: View {
var reportUrl: String
init(reportUrl: String) {
self.reportUrl = reportUrl
}
var body: some View {
VStack {
Button {
presentPrintInteractionController(url: URL(string: reportUrl), jobName: "Print a pdf report") { result in
switch result {
case .success:
print("Print Successful")
case .failure(let error):
print("Error: \(error)")
case .userCancelled:
print("Printing job cancelled.")
}
}
} label: {
Text("Print")
}
}
}
}
struct ReportView_Previews: PreviewProvider {
static var previews: some View {
ReportView(reportUrl: "")
}
}