如何使用Swift

时间:2015-10-18 17:41:02

标签: ios swift amazon-web-services dictionary amazon-dynamodb

我正在尝试使用低级API将字典保存到DynamoDB表字段。我无法弄清楚如何使用对象映射器。在AWS iOS文档中没有这样的示例,我试图不成功地研究和实现同一主题的Java / .NET示例。

我想使用updateExpression仅更新行中的字典字段。

我在寻找答案时偶然发现了这个问题,但没有帮助:Best way to make Amazon AWS DynamoDB queries using Swift?

这是更新dynamoDB-table的功能:

func saveMapToDatabase(hashKey:Int, rangeKey:Double, myDict:[Int:Double]){
    let nsDict:NSDictionary = NSDictionary(dictionary: myDict)
    var dictAsAwsValue = AWSDynamoDBAttributeValue();dictAsAwsValue.M = nsDict as [NSObject : AnyObject]

    let updateInput:AWSDynamoDBUpdateItemInput = AWSDynamoDBUpdateItemInput()
    let hashKeyValue:AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue();hashKeyValue.N = String(hashKey)
    let rangeKeyValue:AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue(); rangeKeyValue.N = String(stringInterpolationSegment: rangeKey)

    updateInput.tableName = "my_table_name"
    updateInput.key = ["db_hash_key" :hashKeyValue, "db_range_key":rangeKeyValue]

    //How I usually do low-level update:
    //let valueUpdate:AWSDynamoDBAttributeValueUpdate = AWSDynamoDBAttributeValueUpdate()
    //valueUpdate.value = dictAsAwsValue
    //valueUpdate.action = AWSDynamoDBAttributeAction.Put
    //updateInput.attributeUpdates = ["db_dictionary_field":valueUpdate]

    //Using the recommended way: updateExpression
    updateInput.expressionAttributeValues = ["dictionary_value":dictAsAwsValue]
    updateInput.updateExpression = "SET db_dictionary_field = :dictionary_value"

    self.dynamoDB.updateItem(updateInput).continueWithBlock{(task:BFTask!)->AnyObject! in
        //do some debug stuff
        println(updateInput.aws_properties())
        println(task.description)

        return nil
    }
}

1 个答案:

答案 0 :(得分:2)

我解决了,问题是AWS要求字典键始终采用String的形式,不允许任何其他类型。

工作解决方案代码段

...
updateInput.tableName = "my_table_name"
updateInput.key = ["db_hash_key" :hashKeyValue, "db_range_key":rangeKeyValue]

let dictionaryInRightFormat:NSDictionary = ["stringKey":dictAsAwsValue]
updateInput.expressionAttributeValues = updateInput.updateExpression = "SET db_dictionary_field = :stringKey"