Skip to content

Commit

Permalink
shut down HTTPClient in example (#4)
Browse files Browse the repository at this point in the history
* HTTPClient needs to be shutdown after use to avoid memory leak

See https://github.com/swift-server/async-http-client/blob/main/README.md#request-response-api

* need to shutdown the HTTPClient before each exit call

Not really recommended programming, but it is to demonstrate the shutdown of the HTTPClient before terminating the program.

* use defer to shutdown the HTTPClient

* http client shutdown in example

---------

Co-authored-by: Simon Leeb <[email protected]>
  • Loading branch information
ronnybremer and sliemeobn authored Jul 13, 2024
1 parent bad39b4 commit d436be5
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 50 deletions.
63 changes: 63 additions & 0 deletions Examples/PrintPDF/app.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Foundation
import IppClient

@main
struct App {
static func main() async throws {
let httpClient = HTTPClient(configuration: .init(certificateVerification: .none))

do {
let printer = IppPrinter(
httpClient: httpClient,
uri: "ipps://macmini.not.local/printers/EPSON_XP_7100_Series"
)

let attributesResponse = try await printer.getPrinterAttributes()

if let printerName = attributesResponse[printer: \.printerName],
let printerState = attributesResponse[printer: \.printerState],
let printerStateReasons = attributesResponse[printer: \.printerStateReasons]
{
print("Printing on \(printerName) in state \(printerState), state reasons \(printerStateReasons)")
} else {
print("Could not read printer attributes, status code \(attributesResponse.statusCode)")
}

let pdf = try Data(contentsOf: URL(fileURLWithPath: "Examples/PrintPDF/hi_mom.pdf"))

let response = try await printer.printJob(
documentFormat: "application/pdf",
data: .bytes(pdf)
)

guard response.statusCode == .successfulOk, let jobId = response[job: \.jobId] else {
print("Print job failed with status \(response.statusCode)")
exit(1)
}

let job = printer.job(jobId)

while true {
let response = try await job.getJobAttributes(requestedAttributes: [.jobState])
guard let jobState = response[job: \.jobState] else {
print("Failed to get job state")
exit(1)
}

switch jobState {
case .aborted, .canceled, .completed:
print("Job ended with state \(jobState)")
exit(0)
default:
print("Job state is \(jobState)")
}

try await Task.sleep(nanoseconds: 3_000_000_000)
}
} catch {
print("Error: \(error)")
}

try await httpClient.shutdown()
}
}
50 changes: 0 additions & 50 deletions Examples/PrintPDF/main.swift

This file was deleted.

0 comments on commit d436be5

Please sign in to comment.