Swift & DynamoDB
AWS Swift integration is not as straightforward as the sheer size and scope of AWS services might make you believe. After a lot of reading and debugging, I worked out some code that makes this fairly straightforward. This code makes use of ObservableObject which I intend to write about in the near future.
import SwiftUI
import Combine
import AWSDynamoDB
class SessionsData: ObservableObject {
let didChange = PassthroughSubject< SessionsData, Never >()
@Published var data: [Sessions] = [] {
didSet {
didChange.send(self)
}
}
init() {
load()
}
func load() {
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
let scanExpression = AWSDynamoDBScanExpression()
scanExpression.limit = 20
var temp : [Sessions] = []
dynamoDBObjectMapper.scan(Sessions.self, expression: scanExpression)
.continueWith(block: { (task:AWSTask< AWSDynamoDBPaginatedOutput >!) -> Any? in
if let error = task.error as NSError? {
print("The request failed. Error: \(error)")
} else if let paginatedOutput = task.result {
for session in paginatedOutput.items as! [Sessions] {
temp.append(session)
}
DispatchQueue.main.async {
self.data = temp
self.didChange.send(self)
}
}
return true
})
}
}
The above class defines an obect that conforms to ObservableObject, a protocol that allows SwiftUI to monitor events on an object and automatically redraw itself on the occurrence of those events. This allows a more obvious separation of the data model and view in Apple's new Protocol Oriented Design Framework.
import SwiftUI
import AWSCore
import AWSDynamoDB
struct Events: View {
@ObservedObject var sessionsData = SessionsData()
var body: some View {
...
}
}
The above code is all a person needs to get started implementing their own ObservedObject protocols and get the data model behind AWS moving!