Swift Requires Chilkat v11.5.0+
Swift
Box: Poll User Events and Save a Checkpoint
See more Box Examples
Poll the authenticated user event stream in bounded batches. The local JSON checkpoint keeps processed event IDs and the next stream position. This single-process demonstration logs events; a production worker should commit its business action, deduplication record, and cursor transactionally and prune old IDs.
See the Box API guide for setup and the complete workflow.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
// See Global Unlock Sample.
// Guide: Box API Guide.
success = false
// Supply an unexpired token obtained with one of the Box authentication examples.
// A token represents a particular user or service account. IDs must be accessible to it.
let curl = CkoHttpCurl()!
curl.setVar(varName: "access_token", varValue: "BOX_ACCESS_TOKEN")
let state = CkoJsonObject()!
let files = CkoFileAccess()!
var statePath: String? = "qa_data/box_events_state.json"
if files.fileExists(path: statePath) == true {
success = state.loadFile(path: statePath)
if success != true {
print("\(state.lastErrorText!)")
return
}
if state.hasMember(jsonPath: "position") != true {
print("Invalid checkpoint: position missing.")
return
}
}
else {
// "now" starts a new subscription. It deliberately skips historical events.
state.updateString(jsonPath: "position", value: "now")
}
curl.setVar(varName: "position", varValue: state.string(of: "position"))
let page = CkoJsonObject()!
let seenPath = CkoStringBuilder()!
var eventId: String?
var nextPosition: String?
var batch: Int = 0
var i: Int
var count: Int
var more: Bool = true
while (more == true) && (batch < 20) {
curl.clearTargetOutput(varName: "*")
let authorizedCommand1 = CkoStringBuilder()!
authorizedCommand1.setString(value: "curl -X GET \"https://api.box.com/2.0/events?stream_type=all&stream_position={{position}}&limit=100\" -H \"Authorization: Bearer {{access_token}}\"")
var headerReplacement1: Int = authorizedCommand1.replace(value: "{{access_token}}", replacement: curl.getVar(varName: "access_token")).intValue
success = curl.doYourThing(targetCurl: authorizedCommand1.getAsString())
if (success != true) || (curl.statusCode.intValue != 200) {
print("Box request failed. HTTP status: \(curl.statusCode.intValue)")
print("Failure reason: \(curl.failReason.intValue)")
print("\(curl.responseBodyStr!)")
return
}
success = curl.getResponseJson(json: page)
if success != true {
print("\(curl.lastErrorText!)")
return
}
count = page.size(ofArray: "entries").intValue
i = 0
while i < count {
page.i = i
eventId = page.string(of: "entries[i].event_id")
if eventId == "" {
print("Event without an event_id; checkpoint not advanced.")
return
}
seenPath.clear()
seenPath.append(value: "seen.")
seenPath.append(value: eventId)
if state.hasMember(jsonPath: seenPath.getAsString()) == false {
// Replace this logging with your idempotent business operation.
// Record success only after that operation succeeds.
print("\(eventId!) \(page.string(of: "entries[i].event_type")!) \(page.string(of: "entries[i].source.id")!)")
state.updateBool(jsonPath: seenPath.getAsString(), value: true)
}
i = i + 1
}
nextPosition = page.string(of: "next_stream_position")
if nextPosition == "" {
print("Missing next_stream_position; checkpoint not advanced.")
return
}
more = (count > 0) && (nextPosition != curl.getVar(varName: "position"))
state.updateString(jsonPath: "position", value: nextPosition)
success = state.writeFile(path: statePath)
if success != true {
print("\(state.lastErrorText!)")
return
}
curl.setVar(varName: "position", varValue: nextPosition)
batch = batch + 1
}
print("Checkpoint saved. Run again later to continue polling.")
}