I can perform a simple Get request on a singular table within AWS dynamoDB however when I expand it to a Batch Request across multiple tables I continue to get a error
validation error detected: Value null at 'requestItems.rip.member.keys' failed to satisfy constraint
I understand this as the values not being passed correctly but I can't see what the issue is with my code
//Create Request Values
AWSDynamoDBGetItemInput *getItem = [AWSDynamoDBGetItemInput new];
AWSDynamoDBAttributeValue *hashValue = [AWSDynamoDBAttributeValue new];
hashValue.S = #"User Test";
getItem.key = #{#"ripId": hashValue};
//Create Request Values 2
AWSDynamoDBGetItemInput *getItem2 = [AWSDynamoDBGetItemInput new];
AWSDynamoDBAttributeValue *hashValue2 = [AWSDynamoDBAttributeValue new];
hashValue2.S = #"User Test";
getItem2.key = #{#"chat": hashValue2};
//Combine to Batch Request
AWSDynamoDBBatchGetItemInput * batchFetch = [AWSDynamoDBBatchGetItemInput new];
batchFetch.requestItems = #{ #"rip": getItem,
#"chat": getItem,};
[[dynamoDB batchGetItem:batchFetch] continueWithBlock:^id(BFTask *task) {
if (!task.error) {
NSLog(#"BOY SUCCES");
} else {
NSLog(#" NO BOY SUCCESS %#",task.error);
}
return nil;
}];
Searched the internet high and low but cannot see a working example of a batch request using iOS Objective C (or swift for that matter).
I have tested both variables on a single Get request and they both work.
You forgot to wrap around AWSDynamoDBAttributeValue in AWSDynamoDBKeysAndAttributes. Here is a simple example from AWSDynamoDBTests.m:
AWSDynamoDBKeysAndAttributes *keysAndAttributes = [AWSDynamoDBKeysAndAttributes new];
keysAndAttributes.keys = #[#{#"hashKey" : attributeValue1},
#{#"hashKey" : attributeValue2}];
keysAndAttributes.consistentRead = #YES;
AWSDynamoDBBatchGetItemInput *batchGetItemInput = [AWSDynamoDBBatchGetItemInput new];
batchGetItemInput.requestItems = #{table1Name: keysAndAttributes};
Since the batch get doesn't map to a class I solved it by doing this instead.
I solved it by doing this,
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
let task1 = dynamoDBObjectMapper.load(User.self, hashKey: "rtP1oQ5DJG", rangeKey: nil)
let task2 = dynamoDBObjectMapper.load(User.self, hashKey: "dbqb1zyUq1", rangeKey: nil)
AWSTask.init(forCompletionOfAllTasksWithResults: [task1, task2]).continueWithBlock { (task) -> AnyObject? in
if let users = task.result as? [User] {
print(users.count)
print(users[0].firstName)
print(users[1].firstName)
}
else if let error = task.error {
print(error.localizedDescription)
}
return nil
}
Swift 3
I was able to get the BatchGet request work with the following code. Hope this helps someone else who's struggling with the lack of Swift Docs.
This code assumes that you've configured your AWSServiceConfiguration in the AppDelegate application didFinishLaunchingWithOptions method.
let DynamoDB = AWSDynamoDB.default()
// define your primary hash keys
let hashAttribute1 = AWSDynamoDBAttributeValue()
hashAttribute1?.s = "NDlFRTdDODEtQzNCOC00QUI5LUFFMzUtRkIyNTJFNERFOTBF"
let hashAttribute2 = AWSDynamoDBAttributeValue()
hashAttribute2?.s = "MjVCNzU3MUQtMEM0NC00NEJELTk5M0YtRTM0QjVDQ0Q1NjlF"
let keys: Array = [["userID": hashAttribute1], ["userID": hashAttribute2]]
let keysAndAttributesMap = AWSDynamoDBKeysAndAttributes()
keysAndAttributesMap?.keys = keys as? [[String : AWSDynamoDBAttributeValue]]
keysAndAttributesMap?.consistentRead = true
let tableMap = ["Your-Table-Name" : keysAndAttributesMap]
let request = AWSDynamoDBBatchGetItemInput()
request?.requestItems = tableMap as? [String : AWSDynamoDBKeysAndAttributes]
request?.returnConsumedCapacity = AWSDynamoDBReturnConsumedCapacity.total
DynamoDB.batchGetItem(request!) { (output, error) in
if output != nil {
print("Batch Query output?.responses?.count:", output!.responses!)
}
if error != nil {
print("Batch Query error:", error!)
}
}
Related
I am new to swift.
I have my dictionary as
monthData =
{
"2018-08-10" = {
accuracy = 71;
attempted = 7;
correct = 5;
reward = Bronze;
};
"2018-08-12" = {
accuracy = 13;
attempted = 15;
correct = 2;
reward = "";
};
"2018-08-13" = {
accuracy = 33;
attempted = 15;
correct = 5;
reward = "";
};
"2018-08-14" = {
accuracy = 100;
attempted = 15;
correct = 15;
reward = Gold;
};
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
"2018-08-21" = {
accuracy = 26;
attempted = 15;
correct = 4;
reward = "";
};
"2018-08-23" = {
accuracy = 46;
attempted = 15;
correct = 7;
reward = "";
};
}
I want to get all the dates for which reward is Gold
Can anyone please help me do that?
What I have tried 'till now is:
for (key,value) in monthData{
let temp = monthData.value(forKey: key as! String) as! NSDictionary
for (key1,value1) in temp{
if((value1 as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
but it outputs the error Could not cast value of type '__NSCFNumber' to 'NSString'
The error occurs because when you are iterating the dictionary you force cast the Int values to String which is not possible
The (highly) recommended Swift way is to use the filter function. This is much more efficient than a loop.
In the closure $0.1 represents the value of the current dictionary ($0.0 would be the key). The result is an array of the date strings.
let data : [String:Any] = ["monthData" : ["2018-08-10": ["accuracy" : 71, "attempted" ... ]]]
if let monthData = data["monthData"] as? [String:[String:Any]] {
let goldData = monthData.filter { $0.1["reward"] as? String == "Gold" }
let allDates = Array(goldData.keys)
print(allDates)
}
The code safely unwraps all optionals.
However if there is only one Gold entry the first function is still more efficient than filter
if let monthData = data["monthData"] as? [String:[String : Any]] {
if let goldData = monthData.first( where: {$0.1["reward"] as? String == "Gold" }) {
let goldDate = goldData.key
print(goldDate)
}
}
In Swift avoid the ObjC runtime (value(forKey:)) and Foundation collection types (NSDictionary) as much as possible.
From the first for in loop, you are getting the NSDictionary in temp variable
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
So, you should directly check .value(forKey:) on temp and get the value for reward.
You should try it like this
for (key,value) in monthData {
let temp = monthData.value(forKey: key as! String) as! NSDictionary
if(((temp.value(forKey: "reward")) as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
Try and share results
EDIT
Please checkout the answer from vadian for in-depth explanation and pure swift approach to achieve the same.
Thanks
I am trying to update an item in my dynamoDB noSQL database. Having some troubles implementing this in swift as there is no swift documentation yet.
I was able to create an item in the database successfully, updating an item seems to be a whole other monster.
Swift Code:
var updatedValue: AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue()
updatedValue.s = self.UserID
let dynamo: AWSDynamoDB = AWSDynamoDB()
let AddToHistory = Users()
AddToHistory?._campany = self.CompanyTextBox.text!
AddToHistory?._personalSite = self.PersonalTitleTextBox.text!
AddToHistory?._facebook = self.FacebookTextBox.text!
AddToHistory?._linkedIn = self.LinkedInTextBox.text!
AddToHistory?._title = self.TitleTextBox.text!
AddToHistory?._bio = self.BioTextBox.text!
let updateInput: AWSDynamoDBUpdateItemInput = AWSDynamoDBUpdateItemInput()
updateInput.tableName = "myTableName"
updateInput.key = ["_userId": updatedValue]
let updatedCompany = AWSDynamoDBAttributeValue()
updatedCompany?.s = AddToHistory?._campany
let updatedFacebook = AWSDynamoDBAttributeValue()
updatedFacebook?.s = AddToHistory?._facebook
let updatedLinkedIn = AWSDynamoDBAttributeValue()
updatedLinkedIn?.s = AddToHistory?._linkedIn
let updatedPersonalSite = AWSDynamoDBAttributeValue()
updatedPersonalSite?.s = AddToHistory?._personalSite
let updatedTitle = AWSDynamoDBAttributeValue()
updatedTitle?.s = AddToHistory?._title
let updatedBio = AWSDynamoDBAttributeValue()
updatedBio?.s = AddToHistory?._bio
updateInput.expressionAttributeValues = [
"_campany" : updatedCompany!,
"_facebook" : updatedFacebook!,
"_linkedIn" : updatedLinkedIn!,
"_personalSite" : updatedPersonalSite!,
"_title" : updatedTitle!,
"_bio" : updatedBio!,
]
updateInput.returnValues = AWSDynamoDBReturnValue.updatedNew
dynamo.updateItem(updateInput).continueOnSuccessWith(block: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
}
return nil
}
)
Not getting any warnings or errors in the editor, however when I run the app and press the button which runs this code, I get this exception thrown:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: '- init is not a valid
initializer. Use + defaultDynamoDB or + DynamoDBForKey: instead.'
Not sure what I am missing here, it must be something to do with the way I am initializing the dynamoDB object. Tried accessing a default method for init, but there is no such method. :(
Any help would be greatly appreciated, thanks in advance!
Thanks to Jake.lange's comment, I realized I could have used the object mapper that i used to create items to update them as well. Heres the code incase others run into this problem :)
//db connection mapper
let objectMapper = AWSDynamoDBObjectMapper.default()
//new instancer of User class
let itemToUpdate:CheckaraUsers = CheckaraUsers()
//populate
itemToUpdate._userId = UserID
itemToUpdate._firstName = FirstName
itemToUpdate._lastName = LastName
itemToUpdate._campany = AddToHistory?._campany
itemToUpdate._facebook = AddToHistory?._facebook
itemToUpdate._linkedIn = AddToHistory?._linkedIn
itemToUpdate._personalSite = AddToHistory?._personalSite
itemToUpdate._title = AddToHistory?._title
itemToUpdate._bio = AddToHistory?._bio
//save to dynamoDB
objectMapper.save(itemToUpdate, completionHandler:{(error: Error?) -> Void in
if let error = error {
print("Amazon DynamoDB Save Error: \(error)")
}
print("Saved Information!!!")
})
Your definition was wrong.
Change this:
let dynamo: AWSDynamoDB = AWSDynamoDB()
to:
let dynamo: AWSDynamoDB = AWSDynamoDB.default()
Query results retrieved
"Adjusted_Lease_Value__c" = "0.0";
"Amount_Financed__c" = "23520.64";
"Assignment_Amount__c" = "19220.21";
"Category__c" = 4;
"Charge_Off_Amount__c" = "0.0";
"Committed_Funds__c" = "19220.21";
"Date_Assigned_Back_to_ACG__c" = "<null>"
How I'm retrieving them:
// Initial Access to Salesforce in order to query data
client.performLogin(accessUsername, password: accessPassword, fail:{ (fail) in
}) { (success) in
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
// This line fails
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as! String
// This works no problem
let AmountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as! String
}
When the query result is "null" it crashes the app. What should I do?
If it may nil then do not use forced conversion.
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as? String
let amountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as? String
}
I'm just beginning working with CloudKit, so bear with me.
Background info
At WWDC 2015, apple gave a talk about CloudKit https://developer.apple.com/videos/wwdc/2015/?id=715
In this talk, they warn against creating chaining queries and instead recommend this tactic:
let firstFetch = CKFetchRecordsOperation(...)
let secondFetch = CKFetchRecordsOperation(...)
...
secondFetch.addDependency(firstFetch)
letQueue = NSOperationQueue()
queue.addOperations([firstFetch, secondFetch], waitUntilFinished: false)
Example structure
The test project database contains pets and their owners, it looks like this:
|Pets | |Owners |
|-name | |-firstName |
|-birthdate | |-lastName |
|-owner (Reference) | | |
My Question
I am trying to find all pets that belong to an owner, and I'm worried I'm creating the chain apple warns against. See below for two methods that do the same thing, but two ways. Which is more correct or are both wrong? I feel like I'm doing the same thing but just using completion blocks instead.
I'm confused about how to change otherSearchBtnClick: to use dependency. Where would I need to add
ownerQueryOp.addDependency(queryOp)
in otherSearchBtnClick:?
#IBAction func searchBtnClick(sender: AnyObject) {
var petString = ""
let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase
let privateDatabase = container.privateCloudDatabase
let predicate = NSPredicate(format: "lastName == '\(ownerLastNameTxt.text)'")
let ckQuery = CKQuery(recordType: "Owner", predicate: predicate)
publicDatabase.performQuery(ckQuery, inZoneWithID: nil) {
record, error in
if error != nil {
println(error.localizedDescription)
} else {
if record != nil {
for owner in record {
let myRecord = owner as! CKRecord
let myReference = CKReference(record: myRecord, action: CKReferenceAction.None)
let myPredicate = NSPredicate(format: "owner == %#", myReference)
let petQuery = CKQuery(recordType: "Pet", predicate: myPredicate)
publicDatabase.performQuery(petQuery, inZoneWithID: nil) {
record, error in
if error != nil {
println(error.localizedDescription)
} else {
if record != nil {
for pet in record {
println(pet.objectForKey("name") as! String)
}
}
}
}
}
}
}
}
}
#IBAction func otherSearchBtnClick (sender: AnyObject) {
let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase
let privateDatabase = container.privateCloudDatabase
let queue = NSOperationQueue()
let petPredicate = NSPredicate(format: "lastName == '\(ownerLastNameTxt.text)'")
let petQuery = CKQuery(recordType: "Owner", predicate: petPredicate)
let queryOp = CKQueryOperation(query: petQuery)
queryOp.recordFetchedBlock = { (record: CKRecord!) in
println("recordFetchedBlock: \(record)")
self.matchingOwners.append(record)
}
queryOp.queryCompletionBlock = { (cursor: CKQueryCursor!, error: NSError!) in
if error != nil {
println(error.localizedDescription)
} else {
println("queryCompletionBlock: \(cursor)")
println("ALL RECORDS ARE: \(self.matchingOwners)")
for owner in self.matchingOwners {
let ownerReference = CKReference(record: owner, action: CKReferenceAction.None)
let ownerPredicate = NSPredicate(format: "owner == %#", ownerReference)
let ownerQuery = CKQuery(recordType: "Pet", predicate: ownerPredicate)
let ownerQueryOp = CKQueryOperation(query: ownerQuery)
ownerQueryOp.recordFetchedBlock = { (record: CKRecord!) in
println("recordFetchedBlock (pet values): \(record)")
self.matchingPets.append(record)
}
ownerQueryOp.queryCompletionBlock = { (cursor: CKQueryCursor!, error: NSError!) in
if error != nil {
println(error.localizedDescription)
} else {
println("queryCompletionBlock (pet values)")
for pet in self.matchingPets {
println(pet.objectForKey("name") as! String)
}
}
}
publicDatabase.addOperation(ownerQueryOp)
}
}
}
publicDatabase.addOperation(queryOp)
}
If you don't need cancellation and aren't bothered about retrying on a network error then I think you are fine chaining the queries.
I know I know, in WWDC 2015 Nihar Sharma recommended the add dependency approach but it would appear he just threw that in at the end without much thought. You see it isn't possible to retry a NSOperation because they are one-shot anyway, and he offered no example for cancelling operations already in the queue, or how to pass data from one operation from the next. Given these 3 complications that could take you weeks to solve, just stick with what you have working and wait for the next WWDC for their solution. Plus the whole point of blocks is to let you call inline methods and be able to access the params in the method above, so if you move to operations you kind of don't get full advantage of that benefit.
His main reason for not using chaining is the ridiculous one that he couldn't tell which error is for which request, he had names his errors someError then otherError etc. No one in their right mind names error params different inside blocks so just use the same name for all of them and then you know inside a block you are always using the right error. Thus he was the one that created his messy scenario and offered a solution for it, however the best solution is just don't create the messy scenario of multiple error param names in the first place!
With all that being said, in case you still want to try to use operation dependencies here is an example of how it could be done:
__block CKRecord* venueRecord;
CKRecordID* venueRecordID = [[CKRecordID alloc] initWithRecordName:#"4c31ee5416adc9282343c19c"];
CKFetchRecordsOperation* fetchVenue = [[CKFetchRecordsOperation alloc] initWithRecordIDs:#[venueRecordID]];
fetchVenue.database = [CKContainer defaultContainer].publicCloudDatabase;
// init a fetch for the category, it's just a placeholder just now to go in the operation queue and will be configured once we have the venue.
CKFetchRecordsOperation* fetchCategory = [[CKFetchRecordsOperation alloc] init];
[fetchVenue setFetchRecordsCompletionBlock:^(NSDictionary<CKRecordID *,CKRecord *> * _Nullable recordsByRecordID, NSError * _Nullable error) {
venueRecord = recordsByRecordID.allValues.firstObject;
CKReference* ref = [venueRecord valueForKey:#"category"];
// configure the category fetch
fetchCategory.recordIDs = #[ref.recordID];
fetchCategory.database = [CKContainer defaultContainer].publicCloudDatabase;
}];
[fetchCategory setFetchRecordsCompletionBlock:^(NSDictionary<CKRecordID *,CKRecord *> * _Nullable recordsByRecordID, NSError * _Nullable error) {
CKRecord* categoryRecord = recordsByRecordID.allValues.firstObject;
// here we have a venue and a category so we could call a completion handler with both.
}];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[fetchCategory addDependency:fetchVenue];
[queue addOperations:#[fetchVenue, fetchCategory] waitUntilFinished:NO];
How it works is first it vetches a Venue record, then it fetches its Category.
Sorry there is no error handling but as you can see it was already a ton of code to do something can could be done in a couple of lines with chaining. And personally I find this result more convoluted and confusing than simply chaining together the convenience methods.
in theory you could have multiple owners and therefore multiple dependencies. Also the inner queries will be created after the outer query is already executed. You will be too late to create a dependency. In your case it's probably easier to force the execution of the inner queries to a separate queue like this:
if record != nil {
for owner in record {
NSOperationQueue.mainQueue().addOperationWithBlock {
This way you will make sure that every inner query will be executed on a new queue and in the mean time that parent query can finish.
Something else: to make your code cleaner, it would be better if all the code inside the for loop was in a separate function with a CKReference as a parameter.
I had the same problem recently and ended up using a NSBlockOperation to prepare the second query and added a dependency to make it all work:
let container = CKContainer.defaultContainer()
let publicDB = container.publicCloudDatabase
let operationqueue = NSOperationQueue.mainQueue()
let familyPredicate = NSPredicate(format: "name == %#", argumentArray: [familyName])
let familyQuery = CKQuery(recordType: "Familias", predicate: familyPredicate)
let fetchFamilyRecordOp = CKQueryOperation(query: familyQuery)
fetchFamilyRecordOp.recordFetchedBlock = { record in
familyRecord = record
}
let fetchMembersOP = CKQueryOperation()
// Once we have the familyRecord, we prepare the PersonsFetch
let prepareFamilyRef = NSBlockOperation() {
let familyRef = CKReference(record: familyRecord!, action: CKReferenceAction.None)
let familyRecordID = familyRef?.recordID
let membersPredicate = NSPredicate(format: "familia == %#", argumentArray: [familyRecordID!])
let membersQuery = CKQuery(recordType: "Personas", predicate: membersPredicate)
fetchMembersOP.query = membersQuery
}
prepareFamilyRef.addDependency(fetchFamilyRecordOp)
fetchMembersOP.recordFetchedBlock = { record in
members.append(record)
}
fetchMembersOP.addDependency(prepareFamilyRef)
fetchMembersOP.database = publicDB
fetchFamilyRecordOp.database = publicDB
operationqueue.addOperations([fetchFamilyRecordOp, fetchMembersOP, prepareFamilyRef], waitUntilFinished: false)
And now it's working as i expected, because you can set up your operations in a very granular way and they execute in the correct order ^.^
in your case i would structure it like this:
let predicate = NSPredicate(format: "lastName == '\(ownerLastNameTxt.text)'")
let ckQuery = CKQuery(recordType: "Owner", predicate: predicate)
let getOwnerOperation = CKQueryOperation(query: ckQuery)
getOwnerOperation.recordFetchedBlock = { record in
let name = record.valueForKey("name") as! String
if name == myOwnerName {
ownerRecord = record
}
}
//now we have and operation that will save in our var OwnerRecord the record that is exactly our owner
//now we create another that will fetch our pets
let queryPetsForOurOwner = CKQueryOperation()
queryPetsForOurOwner.recordFetchedBlock = { record in
results.append(record)
}
//That's all this op has to do, BUT it needs the owner operation to be completed first, but not inmediately, we need to prepare it's query first so:
var fetchPetsQuery : CKQuery?
let preparePetsForOwnerQuery = NSBlockOperation() {
let myOwnerRecord = ownerRecord!
let ownerRef = CKReference(record: myOwnerRecord, action: CKReferenceAction.None)
let myPredicate = NSPredicate(format: "owner == %#", myReference)
fetchPetsQuery = CKQuery(recordType: "Pet", predicate: myPredicate)
}
queryPetsForOurOwner.query = fetchPetsQuery
preparePetsForOwnerQuery.addDependency(getOwnerOperation)
queryPetsForOurOwner.addDependency(preparePetsForOwnerQuery)
and now all it needs to be done is to add them to the newly created operation queue after we direct them to our database
getOwnerOperation.database = publicDB
queryPetsForOurOwner.database = publicDB
let operationqueue = NSOperationQueue.mainQueue()
operationqueue.addOperations([getOwnerOperation, queryPetsForOurOwner, preparePetsForOwnerQuery], waitUntilFinished: false)
P.S: i know i said Family and Person and the names are not like that, but i'm spanish and testing some cloudkit operations, so i haven't standardized to english recor type names yet ;)
I am trying to access the 'address' object (String) in a dictionary:
Chain.sharedInstance().getAddress("19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ"){ dictionary, error in
NSLog("%#", dictionary)
let value = dictionary["address"] as? String //returns nil
}
this is the data I receive:
results = (
{
address = 19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ;
confirmed = {
balance = 0;
received = 20000000;
sent = 20000000;
};
total = {
balance = 0;
received = 20000000;
sent = 20000000;
};
}
); }
How do I access the values in this dictionary when I keep getting nil?
To clarify, the data you are posting is not JSON, but rather looks like JSONP. You aren't showing any code deserializing the the object, so I assume Chain.sharedInstance().getAddress is handling that aspect. If this is an instance of the Bitcoin API, you might look at their documentation. If it is their API, the documentation says the return is
A dictionary with a single "results" key, whose value is a array
containing a single Address Object as a dictionary.
If that is the case if would be
if let resultsArray = dictionary["results"] as NSArray {
if let dict = results[0] as NSDictionary {
//dict["address"] should have your address
}
}
Try:
if let dict = dictionary["results"] as NSDictionary
{
let value = dict["address"] as NSString
}
or:
if let dict = dictionary["results"] as NSArray
{
if let di = dict[0] as NSDictionary
{
let value = di["address"] as NSString
}
}