lundi 25 mai 2015

How to use BFTask with Swift and AWS DynamoDB?

I'm using DynamoDb with swift to make an iPhone application.

I'm trying to query a table I have in my database and then use that queried data to load(query) a different table with the data received.

I'm querying a friends table and then querying a books table. To do this I have a function called queryFriends and queryBooks, which looks like this:

//these are mapper classes for DynamoDB
func queryFriendsTable(hash: Int) -> BFTask! {
    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

    var item = Friends()
    item.UserId = 0
    item.friendId = 0
    let task1 = mapper.save(item)

    let exp = AWSDynamoDBQueryExpression()
    exp.hashKeyValues = hash

    return mapper.query(Friends.self, expression: exp)
}

func loadBooksTable(hash: Int) -> BFTask! {
    let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

    var item = Books()
    item.UserId = 0
    item.name = ""
    item.bookId = 0
    item.author = ""
    let task1 = mapper.save(item)

    return mapper.load(Books.self, hashKey: hash, rangeKey: nil)
}  

I then call these functions in the viewDidLoad section. I use the queryFriendsTable() with a BFTask to call the first query on the friends table and then put the loadBooksTable() inside that function call with another BFTask call.

Here is the code:

//the function is called and takes in "1" as a parameter to query the table with.
self.queryFriendsTable(1).continueWithSuccessBlock{(task: BFTask!) -> BFTask! in
    let results = task.result as! AWSDynamoDBPaginatedOutput

    for r in results.items {
        //this loads the books table and takes the friendId's gotten as an argument
        self.loadBooksTable(r.friendId).continueWithSuccessBlock{ (task: BFTask!) -> BFTask! in
            let books = task.result as! Books
            //this is just a label on the screen to test what I'm doing
            self.testLabel.text = books.name

            return nil
        }
    }

    return nil

}

This works but it takes about 15 seconds for the label to be replaced by the name. I know its not taking that long to get the data though because if I were to do just println(books.name) it takes less then a second to print the name.

So I'm wondering why its taking so long. I tried to google it but I couldn't figure it out. I figure it has something to do with the BFTasks inside eachother but I'm not sure.

Any help is appreciated. Thanks!




Aucun commentaire:

Enregistrer un commentaire