- Swift - 图1influxdb-client-swift
- Swift - 图10Documentation
- Swift - 图11Features
- Swift - 图12Supported Platforms
- Swift - 图13Installation
- Swift - 图15Usage
- Swift - 图27Advanced Usage
- Swift - 图33Contributing
- Swift - 图34License
- influxdb-client-swift
- Documentation
- Features
- Supported Platforms
- Installation
- Swift Package Manager
- Usage
- Creating a client
- Client Options
- Configure default
Bucket,OrganizationandPrecision
- Configure default
- InfluxDB 1.8 API compatibility
- Writes
- Queries
- Query to FluxRecord
- Query to Data
- Parameterized queries
- Delete data
- Management API
- Advanced Usage
- Default Tags
- Example
- Example Output
- Proxy and redirects
- Redirects
- Contributing
- License
Swift - 图1influxdb-client-swift
This repository contains the reference Swift client for the InfluxDB 2.x.
- Features
- Supported Platforms
- Installation
- Swift Package Manager
- Usage
- Creating a client
- Writing data
- Querying data
- Delete data
- Management API
- Advanced Usage
- Default Tags
- Proxy and redirects
- Contributing
- License
Swift - 图10Documentation
This section contains links to the client library documentation.
Swift - 图11Features
InfluxDB 2.x client consists of two packages
InfluxDBSwift- Querying data using the Flux language
- Writing data
- batched in chunks on background
- automatic retries on write failures
InfluxDBSwiftApis- provides all other InfluxDB 2.x APIs for managing
- health check
- sources, buckets
- tasks
- authorizations
- …
- built on top of
InfluxDBSwift
Swift - 图12Supported Platforms
This package requires Swift 5 and Xcode 12+.
- iOS 14.0+
- macOS 11.0+
- tvOS 14.0+
- watchOS 7.0+
- Linux
Swift - 图13Installation
Swift - 图14Swift Package Manager
Add this line to your Package.swift :
1. // swift-tools-version:5.3
2. import PackageDescription
4. let package = Package(
5. name: "MyPackage",
6. dependencies: [
7. .package(name: "influxdb-client-swift", url: "https://github.com/influxdata/influxdb-client-swift", from: "1.6.0"),
8. ],
9. targets: [
10. .target(name: "MyModule", dependencies: [
11. .product(name: "InfluxDBSwift", package: "influxdb-client-swift"),
12. // or InfluxDBSwiftApis for management API
13. .product(name: "InfluxDBSwiftApis", package: "influxdb-client-swift")
14. ])
15. ]
16. )
Swift - 图15Usage
Important: You should call
close()at the end of your application to release allocated resources.
Swift - 图16Creating a client
Specify url and token via parameters:
1. let client = InfluxDBClient(url: "http://localhost:8086", token: "my-token")
3. ...
5. client.close()
Swift - 图17Client Options
| Option | Description | Type | Default |
|---|---|---|---|
| bucket | Default destination bucket for writes | String | none |
| org | Default organization bucket for writes | String | none |
| precision | Default precision for the unix timestamps within the body line-protocol | TimestampPrecision | ns |
| timeoutIntervalForRequest | The timeout interval to use when waiting for additional data. | TimeInterval | 60 sec |
| timeoutIntervalForResource | The maximum amount of time that a resource request should be allowed to take. | TimeInterval | 5 min |
| enableGzip | Enable Gzip compression for HTTP requests. | Bool | false |
| debugging | Enable debugging for HTTP request/response. | Bool | false |
Swift - 图18Configure default Bucket, Organization and Precision
1. let options: InfluxDBClient.InfluxDBOptions = InfluxDBClient.InfluxDBOptions(
2. bucket: "my-bucket",
3. org: "my-org",
4. precision: .ns)
6. let client = InfluxDBClient(url: "http://localhost:8086", token: "my-token", options: options)
8. ...
10. client.close()
Swift - 图19InfluxDB 1.8 API compatibility
1. client = InfluxDBClient(
2. url: "http://localhost:8086",
3. username: "user",
4. password: "pass",
5. database: "my-db",
6. retentionPolicy: "autogen")
8. ...
10. client.close()
Swift - 图20Writes
The WriteApi supports asynchronous writes into InfluxDB 2.x. The results of writes could be handled by (response, error), Swift.Result or Combine.
The data could be written as:
Stringthat is formatted as a InfluxDB’s Line Protocol- Data Point structure
- Tuple style mapping with keys:
measurement,tags,fieldsandtime - Array of above items
The following example demonstrates how to write data with Data Point structure. For further information see docs and examples.
1. import ArgumentParser
2. import Foundation
3. import InfluxDBSwift
4. import InfluxDBSwiftApis
6. @main
7. struct WriteData: AsyncParsableCommand {
8. @Option(name: .shortAndLong, help: "The name or id of the bucket destination.")
9. private var bucket: String
11. @Option(name: .shortAndLong, help: "The name or id of the organization destination.")
12. private var org: String
14. @Option(name: .shortAndLong, help: "Authentication token.")
15. private var token: String
17. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
18. private var url: String
19. }
21. extension WriteData {
22. mutating func run() async throws {
23. //
24. // Initialize Client with default Bucket and Organization
25. //
26. let client = InfluxDBClient(
27. url: url,
28. token: token,
29. options: InfluxDBClient.InfluxDBOptions(bucket: bucket, org: org))
31. //
32. // Record defined as Data Point
33. //
34. let recordPoint = InfluxDBClient
35. .Point("demo")
36. .addTag(key: "type", value: "point")
37. .addField(key: "value", value: .int(2))
38. //
39. // Record defined as Data Point with Timestamp
40. //
41. let recordPointDate = InfluxDBClient
42. .Point("demo")
43. .addTag(key: "type", value: "point-timestamp")
44. .addField(key: "value", value: .int(2))
45. .time(time: .date(Date()))
47. try await client.makeWriteAPI().write(points: [recordPoint, recordPointDate])
48. print("Written data:\n\n\([recordPoint, recordPointDate].map { "\t- \($0)" }.joined(separator: "\n"))")
49. print("\nSuccess!")
51. client.close()
52. }
53. }
- sources - WriteData/WriteData.swift
Swift - 图21Queries
The result retrieved by QueryApi could be formatted as a:
- Lazy sequence of FluxRecord
- Raw query response as a
Data.
Swift - 图22Query to FluxRecord
1. import ArgumentParser
2. import Foundation
3. import InfluxDBSwift
4. import InfluxDBSwiftApis
6. @main
7. struct QueryCpu: AsyncParsableCommand {
8. @Option(name: .shortAndLong, help: "The name or id of the bucket destination.")
9. private var bucket: String
11. @Option(name: .shortAndLong, help: "The name or id of the organization destination.")
12. private var org: String
14. @Option(name: .shortAndLong, help: "Authentication token.")
15. private var token: String
17. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
18. private var url: String
19. }
21. extension QueryCpu {
22. mutating func run() async throws {
23. //
24. // Initialize Client with default Bucket and Organization
25. //
26. let client = InfluxDBClient(
27. url: url,
28. token: token,
29. options: InfluxDBClient.InfluxDBOptions(bucket: bucket, org: org))
31. // Flux query
32. let query = """
33. from(bucket: "\(self.bucket)")
34. |> range(start: -10m)
35. |> filter(fn: (r) => r["_measurement"] == "cpu")
36. |> filter(fn: (r) => r["cpu"] == "cpu-total")
37. |> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
38. |> last()
39. """
41. print("\nQuery to execute:\n\(query)\n")
43. let records = try await client.queryAPI.query(query: query)
45. print("Query results:")
46. try records.forEach { print(" > \($0.values["_field"]!): \($0.values["_value"]!)") }
48. client.close()
49. }
50. }
- sources - QueryCpu/QueryCpu.swift
Swift - 图23Query to Data
1. @main
2. struct QueryCpuData: AsyncParsableCommand {
3. @Option(name: .shortAndLong, help: "The name or id of the bucket destination.")
4. private var bucket: String
6. @Option(name: .shortAndLong, help: "The name or id of the organization destination.")
7. private var org: String
9. @Option(name: .shortAndLong, help: "Authentication token.")
10. private var token: String
12. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
13. private var url: String
14. }
16. extension QueryCpuData {
17. mutating func run() async throws {
18. //
19. // Initialize Client with default Bucket and Organization
20. //
21. let client = InfluxDBClient(
22. url: url,
23. token: token,
24. options: InfluxDBClient.InfluxDBOptions(bucket: bucket, org: org))
26. // Flux query
27. let query = """
28. from(bucket: "\(self.bucket)")
29. |> range(start: -10m)
30. |> filter(fn: (r) => r["_measurement"] == "cpu")
31. |> filter(fn: (r) => r["cpu"] == "cpu-total")
32. |> filter(fn: (r) => r["_field"] == "usage_user" or r["_field"] == "usage_system")
33. |> last()
34. """
36. print("\nQuery to execute:\n\(query)\n")
38. let response = try await client.queryAPI.queryRaw(query: query)
40. let csv = String(decoding: response, as: UTF8.self)
41. print("InfluxDB response: \(csv)")
43. client.close()
44. }
45. }
- sources - QueryCpuData/QueryCpuData.swift
Swift - 图24Parameterized queries
InfluxDB Cloud supports Parameterized Queries that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more reusable and can also be used to help prevent injection attacks.
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named params. Use dot or bracket notation to access parameters in the params record in your Flux query. Parameterized Flux queries support only int , float, and string data types. To convert the supported data types into other Flux basic data types, use Flux type conversion functions.
Parameterized query example:
⚠️ Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
1. import ArgumentParser
2. import Foundation
3. import InfluxDBSwift
4. import InfluxDBSwiftApis
6. @main
7. struct ParameterizedQuery: AsyncParsableCommand {
8. @Option(name: .shortAndLong, help: "The bucket to query. The name or id of the bucket destination.")
9. private var bucket: String
11. @Option(name: .shortAndLong,
12. help: "The organization executing the query. Takes either the `ID` or `Name` interchangeably.")
13. private var org: String
15. @Option(name: .shortAndLong, help: "Authentication token.")
16. private var token: String
18. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
19. private var url: String
20. }
22. extension ParameterizedQuery {
23. mutating func run() async throws {
24. // Initialize Client with default Organization
25. let client = InfluxDBClient(
26. url: url,
27. token: token,
28. options: InfluxDBClient.InfluxDBOptions(bucket: bucket, org: org))
30. for index in 1...3 {
31. let point = InfluxDBClient
32. .Point("demo")
33. .addTag(key: "type", value: "point")
34. .addField(key: "value", value: .int(index))
35. try await client.makeWriteAPI().write(point: point)
36. }
38. // Flux query
39. let query = """
40. from(bucket: params.bucketParam)
41. |> range(start: -10m)
42. |> filter(fn: (r) => r["_measurement"] == params.measurement)
43. """
45. // Query parameters [String:String]
46. let queryParams = ["bucketParam": "\(bucket)", "measurement": "demo"]
48. print("\nQuery to execute:\n\n\(query)\n\n\(queryParams)")
50. let records = try await client.queryAPI.query(query: query, params: queryParams)
52. print("\nSuccess response...\n")
54. try records.forEach { print(" > \($0.values["_field"]!): \($0.values["_value"]!)") }
56. client.close()
57. }
58. }
Swift - 图25Delete data
The DeleteAPI supports deletes points from an InfluxDB bucket. Use the DeletePredicateRequest identifies which points to delete.
1. import ArgumentParser
2. import Foundation
3. import InfluxDBSwift
4. import InfluxDBSwiftApis
6. @main
7. struct DeleteData: AsyncParsableCommand {
8. @Option(name: .shortAndLong, help: "Specifies the bucket name to delete data from.")
9. private var bucket: String
11. @Option(name: .shortAndLong,
12. help: "Specifies the organization name to delete data from.")
13. private var org: String
15. @Option(name: .shortAndLong, help: "Authentication token.")
16. private var token: String
18. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
19. private var url: String
21. @Option(name: .shortAndLong, help: "InfluxQL-like delete predicate statement.")
22. private var predicate: String
23. }
25. extension DeleteData {
26. mutating func run() async throws {
27. // Initialize Client with default Organization
28. let client = InfluxDBClient(
29. url: url,
30. token: token,
31. options: InfluxDBClient.InfluxDBOptions(org: self.org))
33. // Create DeletePredicateRequest
34. let predicateRequest = DeletePredicateRequest(
35. start: Date(timeIntervalSince1970: 0),
36. stop: Date(),
37. predicate: predicate)
39. try await client.deleteAPI.delete(predicate: predicateRequest, bucket: bucket, org: org)
41. print("\nDeleted data by predicate:\n\n\t\(predicateRequest)")
43. // Print date after Delete
44. try await queryData(client: client)
46. client.close()
47. }
49. private func queryData(client: InfluxDBClient) async throws {
50. let query = """
51. from(bucket: "\(bucket)")
52. |> range(start: 0)
53. |> filter(fn: (r) => r["_measurement"] == "server")
54. |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
55. """
57. let response = try await client.queryAPI.query(query: query)
59. print("\nRemaining data after delete:\n")
61. try response.forEach { record in
62. let provider = record.values["provider"]!
63. let production = record.values["production"]
64. let app = record.values["app"]
65. return print("\t\(provider),production=\(production!),app=\(app!)")
66. }
67. }
68. }
- sources - DeleteData/DeleteData.swift
Swift - 图26Management API
The client supports following management API:
| API docs | |
|---|---|
| AuthorizationsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Authorizations> |
| BucketsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Buckets> |
| DBRPsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/DBRPs> |
| HealthAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Health> |
| PingAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Ping> |
| LabelsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Labels> |
| OrganizationsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Organizations> |
| ReadyAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Ready> |
| ScraperTargetsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/ScraperTargets> |
| SecretsAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Secrets> |
| SetupAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Tasks> |
| SourcesAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Sources> |
| TasksAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Tasks> |
| UsersAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Users> |
| VariablesAPI | <https://docs.influxdata.com/influxdb/latest/api/#tag/Variables> |
The following example demonstrates how to use a InfluxDB 2.0 Management API to create new bucket. For further information see docs and examples.
1. import ArgumentParser
2. import Foundation
3. import InfluxDBSwift
4. import InfluxDBSwiftApis
6. @main
7. struct CreateNewBucket: AsyncParsableCommand {
8. @Option(name: .shortAndLong, help: "New bucket name.")
9. private var name: String
11. @Option(name: .shortAndLong, help: "Duration bucket will retain data.")
12. private var retention: Int64 = 3600
14. @Option(name: .shortAndLong, help: "Specifies the organization name.")
15. private var org: String
17. @Option(name: .shortAndLong, help: "Authentication token.")
18. private var token: String
20. @Option(name: .shortAndLong, help: "HTTP address of InfluxDB.")
21. private var url: String
22. }
24. extension CreateNewBucket {
25. mutating func run() async throws {
26. // Initialize Client and API
27. let client = InfluxDBClient(url: url, token: token)
28. let api = InfluxDB2API(client: client)
30. let orgId = (try await api.organizationsAPI.getOrgs(org: org)!).orgs?.first?.id
32. // Bucket configuration
33. let request = PostBucketRequest(
34. orgID: orgId!,
35. name: name,
36. retentionRules: [RetentionRule(type: RetentionRule.ModelType.expire, everySeconds: retention)])
38. // Create Bucket
39. let bucket = try await api.bucketsAPI.postBuckets(postBucketRequest: request)!
41. // Create Authorization with permission to read/write created bucket
42. let bucketResource = Resource(
43. type: Resource.ModelType.buckets,
44. id: bucket.id,
45. orgID: orgId
46. )
48. // Authorization configuration
49. let authorizationRequest = AuthorizationPostRequest(
50. description: "Authorization to read/write bucket: \(name)",
51. orgID: orgId!,
52. permissions: [
53. Permission(action: Permission.Action.read, resource: bucketResource),
54. Permission(action: Permission.Action.write, resource: bucketResource)
55. ])
57. // Create Authorization
58. let authorization = try await api.authorizationsAPI.postAuthorizations(authorizationPostRequest: authorizationRequest)!
60. print("The bucket: '\(bucket.name)' is successfully created.")
61. print("The following token could be use to read/write:")
62. print("\t\(authorization.token!)")
64. client.close()
65. }
66. }
- sources - CreateNewBucket/CreateNewBucket.swift
Swift - 图27Advanced Usage
Swift - 图28Default Tags
Sometimes is useful to store same information in every measurement e.g. hostname, location, customer. The client is able to use static value or env variable as a tag value.
The expressions:
California Miner- static value${env.HOST_NAME}- environment property
Swift - 图29Example
1. client = InfluxDBClient(
2. url: "http://localhost:8086",
3. token: "my-token",
4. options: InfluxDBClient.InfluxDBOptions(bucket: "my-bucket", org: "my-org"))
6. let tuple: InfluxDBClient.Point.Tuple
7. = (measurement: "mem", tags: ["tag": "a"], fields: ["value": .int(3)], time: nil)
9. let records: [Any] = [
10. InfluxDBClient.Point("mining")
11. .addTag(key: "sensor_state", value: "normal")
12. .addField(key: "depth", value: .int(2)),
13. tuple
14. ]
16. let defaultTags = InfluxDBClient.PointSettings()
17. .addDefaultTag(key: "customer", value: "California Miner")
18. .addDefaultTag(key: "sensor_id", value: "${env.SENSOR_ID}")
20. try await client.makeWriteAPI(pointSettings: defaultTags).writeRecords(records: records)
21. print("Successfully written default tags")
Swift - 图30Example Output
1. mining,customer=California\ Miner,sensor_id=123-456-789,sensor_state=normal depth=2i
2. mining,customer=California\ Miner,sensor_id=123-456-789,sensor_state=normal pressure=3i
Swift - 图31Proxy and redirects
⚠️ The
connectionProxyDictionarycannot be defined on Linux. You have to setHTTPS_PROXYorHTTP_PROXYsystem environment.
You can configure the client to tunnel requests through an HTTP proxy by connectionProxyDictionary option:
1. var connectionProxyDictionary = [AnyHashable: Any]()
2. connectionProxyDictionary[kCFNetworkProxiesHTTPEnable as String] = 1
3. connectionProxyDictionary[kCFNetworkProxiesHTTPProxy as String] = "localhost"
4. connectionProxyDictionary[kCFNetworkProxiesHTTPPort as String] = 3128
6. let options: InfluxDBClient.InfluxDBOptions = InfluxDBClient.InfluxDBOptions(
7. bucket: "my-bucket",
8. org: "my-org",
9. precision: .ns,
10. connectionProxyDictionary: connectionProxyDictionary)
12. client = InfluxDBClient(url: "http://localhost:8086", token: "my-token", options: options)
For more info see - URLSessionConfiguration.connectionProxyDictionary, Global Proxy Settings Constants.
Swift - 图32Redirects
Client automatically follows HTTP redirects. You can disable redirects by an urlSessionDelegate configuration:
1. class DisableRedirect: NSObject, URLSessionTaskDelegate {
2. func urlSession(_ session: URLSession,
3. task: URLSessionTask,
4. willPerformHTTPRedirection response: HTTPURLResponse,
5. newRequest request: URLRequest,
6. completionHandler: @escaping (URLRequest?) -> Void) {
7. completionHandler(nil)
8. }
9. }
11. let options = InfluxDBClient.InfluxDBOptions(
12. bucket: "my-bucket",
13. org: "my-org",
14. urlSessionDelegate: DisableRedirect())
16. client = InfluxDBClient(url: "http://localhost:8086", token: "my-token", options: options)
For more info see - URLSessionDelegate.
Swift - 图33Contributing
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.
Build Requirements:
- swift 5.3 or higher
Build source and test targets:
1. swift build --build-tests
Run tests:
1. ./Scripts/influxdb-restart.sh
2. swift test
Check code coverage:
1. ./Scripts/influxdb-restart.sh
2. swift test --enable-code-coverage
You could also use a docker-cli without installing the Swift SDK:
1. make docker-cli
2. swift build
Swift - 图34License
The client is available as open source under the terms of the MIT License.

