Wählen Sie Ihre Cookie-Einstellungen aus

Wir verwenden essentielle Cookies und ähnliche Tools, die für die Bereitstellung unserer Website und Services erforderlich sind. Wir verwenden Performance-Cookies, um anonyme Statistiken zu sammeln, damit wir verstehen können, wie Kunden unsere Website nutzen, und Verbesserungen vornehmen können. Essentielle Cookies können nicht deaktiviert werden, aber Sie können auf „Anpassen“ oder „Ablehnen“ klicken, um Performance-Cookies abzulehnen.

Wenn Sie damit einverstanden sind, verwenden AWS und zugelassene Drittanbieter auch Cookies, um nützliche Features der Website bereitzustellen, Ihre Präferenzen zu speichern und relevante Inhalte, einschließlich relevanter Werbung, anzuzeigen. Um alle nicht notwendigen Cookies zu akzeptieren oder abzulehnen, klicken Sie auf „Akzeptieren“ oder „Ablehnen“. Um detailliertere Entscheidungen zu treffen, klicken Sie auf „Anpassen“.

Amazon SQS examples using SDK for Swift - AWS SDK Code Examples
Diese Seite wurde nicht in Ihre Sprache übersetzt. Übersetzung anfragen

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Amazon SQS examples using SDK for Swift

The following code examples show you how to perform actions and implement common scenarios by using the AWS SDK for Swift with Amazon SQS.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

Each example includes a link to the complete source code, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Amazon SQS.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

The Package.swift file.

import PackageDescription let package = Package( name: "sqs-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sqs-basics", dependencies: [ .product(name: "AWSSQS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument-parser") ], path: "Sources") ] )

The Swift source code, entry.swift.

import ArgumentParser import AWSClientRuntime import AWSSQS import Foundation struct ExampleCommand: ParsableCommand { @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "sqs-basics", abstract: """ This example shows how to list all of your available Amazon SQS queues. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) var queues: [String] = [] let outputPages = sqsClient.listQueuesPaginated( input: ListQueuesInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } } print("You have \(queues.count) queues:") for queue in queues { print(" \(queue)") } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } }
  • For API details, see ListQueues in AWS SDK for Swift API reference.

The following code examples show how to get started using Amazon SQS.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

The Package.swift file.

import PackageDescription let package = Package( name: "sqs-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sqs-basics", dependencies: [ .product(name: "AWSSQS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument-parser") ], path: "Sources") ] )

The Swift source code, entry.swift.

import ArgumentParser import AWSClientRuntime import AWSSQS import Foundation struct ExampleCommand: ParsableCommand { @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "sqs-basics", abstract: """ This example shows how to list all of your available Amazon SQS queues. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) var queues: [String] = [] let outputPages = sqsClient.listQueuesPaginated( input: ListQueuesInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } } print("You have \(queues.count) queues:") for queue in queues { print(" \(queue)") } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } }
  • For API details, see ListQueues in AWS SDK for Swift API reference.

Topics

Actions

The following code example shows how to use CreateQueue.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.createQueue( input: CreateQueueInput( queueName: queueName ) ) guard let queueUrl = output.queueUrl else { print("No queue URL returned.") return }
  • For API details, see CreateQueue in AWS SDK for Swift API reference.

The following code example shows how to use CreateQueue.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.createQueue( input: CreateQueueInput( queueName: queueName ) ) guard let queueUrl = output.queueUrl else { print("No queue URL returned.") return }
  • For API details, see CreateQueue in AWS SDK for Swift API reference.

The following code example shows how to use DeleteMessageBatch.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) // Create the list of message entries. var entries: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] var messageNumber = 1 for handle in handles { let entry = SQSClientTypes.DeleteMessageBatchRequestEntry( id: "\(messageNumber)", receiptHandle: handle ) entries.append(entry) messageNumber += 1 } // Delete the messages. let output = try await sqsClient.deleteMessageBatch( input: DeleteMessageBatchInput( entries: entries, queueUrl: queue ) ) // Get the lists of failed and successful deletions from the output. guard let failedEntries = output.failed else { print("Failed deletion list is missing!") return } guard let successfulEntries = output.successful else { print("Successful deletion list is missing!") return } // Display a list of the failed deletions along with their // corresponding explanation messages. if failedEntries.count != 0 { print("Failed deletions:") for entry in failedEntries { print("Message #\(entry.id ?? "<unknown>") failed: \(entry.message ?? "<unknown>")") } } else { print("No failed deletions.") } // Output a list of the message numbers that were successfully deleted. if successfulEntries.count != 0 { var successes = "" for entry in successfulEntries { if successes.count == 0 { successes = entry.id ?? "<unknown>" } else { successes = "\(successes), \(entry.id ?? "<unknown>")" } } print("Succeeded: ", successes) } else { print("No successful deletions.") }

The following code example shows how to use DeleteMessageBatch.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) // Create the list of message entries. var entries: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] var messageNumber = 1 for handle in handles { let entry = SQSClientTypes.DeleteMessageBatchRequestEntry( id: "\(messageNumber)", receiptHandle: handle ) entries.append(entry) messageNumber += 1 } // Delete the messages. let output = try await sqsClient.deleteMessageBatch( input: DeleteMessageBatchInput( entries: entries, queueUrl: queue ) ) // Get the lists of failed and successful deletions from the output. guard let failedEntries = output.failed else { print("Failed deletion list is missing!") return } guard let successfulEntries = output.successful else { print("Successful deletion list is missing!") return } // Display a list of the failed deletions along with their // corresponding explanation messages. if failedEntries.count != 0 { print("Failed deletions:") for entry in failedEntries { print("Message #\(entry.id ?? "<unknown>") failed: \(entry.message ?? "<unknown>")") } } else { print("No failed deletions.") } // Output a list of the message numbers that were successfully deleted. if successfulEntries.count != 0 { var successes = "" for entry in successfulEntries { if successes.count == 0 { successes = entry.id ?? "<unknown>" } else { successes = "\(successes), \(entry.id ?? "<unknown>")" } } print("Succeeded: ", successes) } else { print("No successful deletions.") }

The following code example shows how to use DeleteQueue.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.deleteQueue( input: DeleteQueueInput( queueUrl: queueUrl ) ) } catch _ as AWSSQS.QueueDoesNotExist { print("Error: The specified queue doesn't exist.") return }
  • For API details, see DeleteQueue in AWS SDK for Swift API reference.

The following code example shows how to use DeleteQueue.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.deleteQueue( input: DeleteQueueInput( queueUrl: queueUrl ) ) } catch _ as AWSSQS.QueueDoesNotExist { print("Error: The specified queue doesn't exist.") return }
  • For API details, see DeleteQueue in AWS SDK for Swift API reference.

The following code example shows how to use GetQueueAttributes.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.getQueueAttributes( input: GetQueueAttributesInput( attributeNames: [ .approximatenumberofmessages, .maximummessagesize ], queueUrl: url ) ) guard let attributes = output.attributes else { print("No queue attributes returned.") return } for (attr, value) in attributes { switch(attr) { case "ApproximateNumberOfMessages": print("Approximate message count: \(value)") case "MaximumMessageSize": print("Maximum message size: \(value)kB") default: continue } }

The following code example shows how to use GetQueueAttributes.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.getQueueAttributes( input: GetQueueAttributesInput( attributeNames: [ .approximatenumberofmessages, .maximummessagesize ], queueUrl: url ) ) guard let attributes = output.attributes else { print("No queue attributes returned.") return } for (attr, value) in attributes { switch(attr) { case "ApproximateNumberOfMessages": print("Approximate message count: \(value)") case "MaximumMessageSize": print("Maximum message size: \(value)kB") default: continue } }

The following code example shows how to use ListQueues.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) var queues: [String] = [] let outputPages = sqsClient.listQueuesPaginated( input: ListQueuesInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } }
  • For API details, see ListQueues in AWS SDK for Swift API reference.

The following code example shows how to use ListQueues.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) var queues: [String] = [] let outputPages = sqsClient.listQueuesPaginated( input: ListQueuesInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } }
  • For API details, see ListQueues in AWS SDK for Swift API reference.

The following code example shows how to use ReceiveMessage.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.receiveMessage( input: ReceiveMessageInput( maxNumberOfMessages: maxMessages, queueUrl: url ) ) guard let messages = output.messages else { print("No messages received.") return } for message in messages { print("Message ID: \(message.messageId ?? "<unknown>")") print("Receipt handle: \(message.receiptHandle ?? "<unknown>")") print(message.body ?? "<body missing>") print("---") }
  • For API details, see ReceiveMessage in AWS SDK for Swift API reference.

The following code example shows how to use ReceiveMessage.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.receiveMessage( input: ReceiveMessageInput( maxNumberOfMessages: maxMessages, queueUrl: url ) ) guard let messages = output.messages else { print("No messages received.") return } for message in messages { print("Message ID: \(message.messageId ?? "<unknown>")") print("Receipt handle: \(message.receiptHandle ?? "<unknown>")") print(message.body ?? "<body missing>") print("---") }
  • For API details, see ReceiveMessage in AWS SDK for Swift API reference.

The following code example shows how to use SetQueueAttributes.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.setQueueAttributes( input: SetQueueAttributesInput( attributes: [ "MaximumMessageSize": "\(maxSize)" ], queueUrl: url ) ) } catch _ as AWSSQS.InvalidAttributeValue { print("Invalid maximum message size: \(maxSize) kB.") }

The following code example shows how to use SetQueueAttributes.

SDK for Swift
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.setQueueAttributes( input: SetQueueAttributesInput( attributes: [ "MaximumMessageSize": "\(maxSize)" ], queueUrl: url ) ) } catch _ as AWSSQS.InvalidAttributeValue { print("Invalid maximum message size: \(maxSize) kB.") }
DatenschutzNutzungsbedingungen für die WebsiteCookie-Einstellungen
© 2025, Amazon Web Services, Inc. oder Tochtergesellschaften. Alle Rechte vorbehalten.