AWS DynamoDB Swift – Query

To query items in a DynamoDB using swift.

(I will be using the example based here, translated to use swift). You can find the source files here: Github

Here is what my table looks like in aws:

dynaboDB-table-example

You first have to define a Mapping Class. Basically this is where you define what values from the table you need to get:


//class that gets the objects from db
class DDBTableRow :AWSDynamoDBObjectModel ,AWSDynamoDBModeling  {
    
    var ISBN:String?
    var Title:String?
    var Author:String?
    

    class func dynamoDBTableName() -> String! {
        return "Books"
    }

    
// if we define attribute it must be included when calling it in function testing...
    class func hashKeyAttribute() -> String! {
        return "ISBN"
    }
    


    class func ignoreAttributes() -> Array<AnyObject>! {
        return nil
    }
    
    //MARK: NSObjectProtocol hack
    //Fixes Does not conform to the NSObjectProtocol error

    override func isEqual(object: AnyObject?) -> Bool {
        return super.isEqual(object)
    }
    
    override func `self`() -> Self {
        return self
    }
}

Once you have the class implementation, then you can begin the querying. Here I created a function called getQuery the returns the values:


    func getQuery(){
        //performing a query
        
        //first create expression
        let queryExpression = AWSDynamoDBQueryExpression()
        
        //second define the index name
        queryExpression.indexName = "Author-index"
        
        //3rd hashes
        queryExpression.hashKeyAttribute = "Author"
        queryExpression.hashKeyValues = ("Jose Deras")
        
        
        //putting it all together
        let dynamoDBObjectMapper2 = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
        
        
        dynamoDBObjectMapper2.query(DDBTableRow.self, expression: queryExpression) .continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
            if (task.error == nil) {
                if (task.result != nil) {
                    NSLog("Somthing happened")
                    //starting the output of data
                    let tableRow = task.result as! AWSDynamoDBPaginatedOutput
                    for (items) in tableRow.items {
                        print("\(items.ISBN)")
                        print("\(items.Title)")
                        print("\(items.Author)")
                    }
                }
            }
            else {
                print("Error: \(task.error)")
                
            }
            return nil
        })
        
        
    }

If you get this error message:

session task failed with error: Error Domain=NSURLErrorDomain Code=-1200 “An SSL error has occurred and a secure connection to the server cannot be made.” UserInfo={_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x7fbcb38103c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 “(null)” UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9824, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9824}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://dynamodb.us-east-1.amazonaws.com/, NSErrorFailingURLStringKey=https://dynamodb.us-east-1.amazonaws.com/, _kCFStreamErrorDomainKey=3}

Add the following to info.plist:

 <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

Adding this disables App transport security that was implemented in iOS9. See more info here.

5 thoughts on “AWS DynamoDB Swift – Query”

  1. Thanks for this!! Really helped me!!
    Is there a way to ask you for a tutorial? Since they have made the Cognito Beta, all the swift examples that they provide doesn’t work, because now, Cognito uses User Pools.
    Is there a way you to post a very simple tutorial where you show how to login via facebook and cognito?
    I would really appreciate it…

  2. I am getting this error
    dispatch_once(predicate, block); signal sigabrt
    libc++abi.dylib: terminating with uncaught exception of type NSException..

    I dont know whats happening.

Leave a Reply

Your email address will not be published. Required fields are marked *