Let me preface this question by saying that I'm very new to coding with Swift and in iOS in general. I've got some experience in Java/Android and am starting to work with iOS as well now.
I need to query a dynamodb table with enough data in it that Amazon paginates the results (I think the limit is 100kb). Using the limited examples for AWS/Swift I am able to query that table but only successfully retrieve the first page of data. My question is how to get that 2nd, 3rd, etc page of data. See code below
let queryExpression = AWSDynamoDBQueryExpression()
queryExpression.keyConditionExpression = "venue_event = :ev"
queryExpression.expressionAttributeValues = [":ev" : "event"]
dynamoDBObjectMapper.query(Event.self, expression: queryExpression).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: {(task:AWSTask!) -> AnyObject! in
let results = task.result as! AWSDynamoDBPaginatedOutput
for r in results.items{
print (r)
}
return nil
})
I've noticed that 'results' has a lastEvaluatedKey variable and loadNextPage method. However I can't seem to get either to give me the function I'm looking for
Thanks in advance for the help
Simply:
var paginatedOutput: AWSDynamoDBPaginatedOutput?
...
self.paginatedOutput = task.result as! AWSDynamoDBPaginatedOutput
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NoSQLQueryResultCell", forIndexPath: indexPath) as! NoSQLQueryResultCell
...
if (!loading) && (paginatedOutput?.lastEvaluatedKey != nil) && indexPath.section == self.results!.count - 1 {
self.loadMoreResults()
}
return cell
}
func loadMoreResults() {
loading = true
paginatedOutput?.loadNextPageWithCompletionHandler({(error: NSError?) -> Void in
if error != nil {
print("Failed to load more results: \(error)")
dispatch_async(dispatch_get_main_queue(), {
self.showAlertWithTitle("Error", message: "Failed to load more more results: \(error?.localizedDescription)")
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
self.results!.appendContentsOf(self.paginatedOutput!.items)
self.tableView.reloadData()
self.loading = false
})
}
})
}
You can download MobileHub Sample code:
This map help:
Related
I am struggling with UITableView's data fetching and/or reloadData() from server. I am creating this app to check user's pronunciation via server. The data parsing came out well (I checked with print statement) but it won't update to my table cell.
I created a dictionary to store loaded Data:
var summaryDict = ["Overall Score" : "Score", "Words" : "Score", "Syllables": "Score", "Phonemes": "Score"]
var summaryArray = ["Overall Score", "Words", "Syllables", "Phonemes"]
I did also update dict values after parsing JSON data:
.responseJSON { response in
switch response.result {
case .success:
do{
let json = try JSON(data: response.data!)
if let data = response.data {
if let summaryData = self.parseJSON(data) {
DispatchQueue.main.async {
print(summaryData)
self.summaryDict["Overall Score"] = summaryData.summaryScore
self.summaryDict["Words"] = summaryData.wordScore
self.summaryDict["Syllables"] = summaryData.syllableScore
self.summaryDict["Phonemes"] = summaryData.phoneScore
print(self.summaryDict)
self.delegate?.didUpdateScore(self, score: summaryData)
}
}
}
let statusJson = json["status"].string
if statusJson == "success" {
completion("success")
}
else { completion("error parseJSON") }
} catch {
print(error.localizedDescription)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
}
Over my ViewController I did also added tableview datasource extension:
extension FreeTrialViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return audioSender.summaryDict.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SummaryCell", for: indexPath) as! SummaryCell
cell.summaryLabel.text = self.audioSender.summaryArray[indexPath.row]
cell.summaryScore.text = self.audioSender.summaryDict[self.audioSender.summaryArray[indexPath.row]]
return cell
}
}
I tried to put reloadData() everywhere I can or DispatchQueue.main.async every now and then yet the cell did not update.
EDITED: Include delegate at view controller:
extension FreeTrialViewController: AudioSenderDelegate {
func didFailWithError(_ error: Error) {
print("parsing audio delegate error: \(error)")
}
func didUpdateScore(_ audioSender: AudioSender, score: SummaryData) {
// updateTable()
summaryTable.reloadData()
}
}
Here's the end result after multiple tries:
(when I took the picture I mistakenly deleted 1 char from the "Overall Score" from the array so the Overall Score disappeared but when I corrected it it goes for 4 "Score".
What I want in the table:
Overall Score: 97
Words: 96.8
Syllable: 96.9
Phonemes: 97.0
What really showed up:
EDITED:
I shall include here the func that I call out the table:
Pretty sure inside the finish recording is the parse data.
I did try adding the guard as:
guard audioSender.summaryDict["Words"] != "Score" else { return }
Yet it would come out blank.
It seems like I forgot to add the line:
audioSender.delegate = self
so the data won't reload.
Thanks so much for all of your help.
Such a shame on me :).
I have been implementing code that is to enable paging scroll to fetch data by a certain amount of data from firebase database.
Firstly, then error says
Terminating app due to uncaught exception 'InvalidQueryParameter',
reason: 'Can't use queryEndingAtValue: with other types than string in
combination with queryOrderedByKey'
The below here is the actual code that produced the above error
static func fetchPostsWith(last_key: String?, completion: #escaping (([PostModel]?) -> Void)) {
var posts = [PostModel]()
let count = 2
let ref = Database.database().reference().child(PATH.all_posts)
let this_key = UInt(count + 1)
let that_key = UInt(count)
let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: this_key)
let that = ref.queryOrderedByKey().queryLimited(toLast: that_key)
let query = (last_key != nil) ? this : that
query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for snap in snapshot.children {
if let d = snap as? DataSnapshot {
let post = PostModel(snapshot: d)
print(post.key ?? "")
posts.append(post)
}
}
posts.sort { $0.date! > $1.date! }
posts = Array(posts.dropFirst())
completion(posts)
} else {
completion(nil)
}
}
}
What it tries to do is to fetch a path where all posts are stored by auto id. But the error keeps coming out so I do not know what is wrong. Do you have any idea?
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// index is the last and last fetched then
print(self.feeds.count - 1 == indexPath.row, "index ", self.hasFetchedLastPage, "has fetched last")
if self.feeds.count - 1 == indexPath.row {
let lastKey = self.feeds[indexPath.row].key
if lastKey != self.previousKey {
self.getFeeds(lastKey: lastKey)
} else {
self.previousKey = lastKey ?? ""
}
}
print("Cell Display Number", indexPath.row)
}
func getFeeds(lastKey: String?) {
print(self.isFetching, "is fetching")
guard !self.isFetching else {
self.previousKey = ""
return
}
self.isFetching = true
print(self.isFetching, "is fetching")
FirebaseModel.fetchPostsWith(last_key: lastKey) { ( d ) in
self.isFetching = false
if let data = d {
if self.feeds.isEmpty { //It'd be, when it's the first time.
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Initial Load", lastKey ?? "no key")
} else {
self.hasFetchedLastPage = self.feeds.count < 2
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Reloaded", lastKey ?? "no key")
}
}
}
}
I want to implement a paging enabled tableView. If you can help this code to be working, it is very appreciated.
You're converting your last_key to a number, while keys are always strings. The error message tells you that the two types are not compatible. This means you must convert your number back to a string in your code, before passing it to the query:
let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: String(this_key))
let that = ref.queryOrderedByKey().queryLimited(toLast: String(that_key))
I am trying to create a tableView of users from my Parse database that are in the same class (at school). All users have to have a username, but not all will have given the app their full name or set a profile picture. I use this code:
let studentsQuery = PFQuery(className:"_User")
studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject])
let query2 = PFQuery.orQueryWithSubqueries([studentsQuery])
query2.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error != nil {
// Display error in tableview
} else if results! == [] {
spinningActivity.hideAnimated(true)
print("error")
} else if results! != [] {
if let objects = results {
for object in objects {
if object.objectForKey("full_name") != nil {
let studentName = object.objectForKey("full_name")! as! String
self.studentNameResults.append(studentName)
}
if object.objectForKey("username") != nil {
let studentUsername = object.objectForKey("username")! as! String
self.studentUsernameResults.append(studentUsername)
}
if object.objectForKey("profile_picture") != nil {
let studentProfilePictureFile = object.objectForKey("profile_picture") as! PFFile
studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in
if error == nil {
let studentProfilePicture : UIImage = UIImage(data: image!)!
self.studentProfilePictureResults.append(studentProfilePicture)
} else {
print("Can't get profile picture")
// Can't get profile picture
}
self.studentsTableView.reloadData()
})
spinningActivity.hideAnimated(true)
} else {
// no image
}
}
}
} else {
spinningActivity.hideAnimated(true)
print("error")
}
}
This code works fine if all of the users have a username, full_name, and a profile_picture. I can't figure out, however, how to get a tableView of the usernames of a user and add a user's name or picture to the user's corresponding tableViewCell only if the user has a picture. Here is how my tableView is configured:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return studentUsernameResults.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell
cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width / 2
cell.studentProfilePictureImageView.clipsToBounds = true
cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row]
cell.studentUsernameLabel.text = studentUsernameResults[indexPath.row]
cell.studentNameLabel.text = studentNameResults[indexPath.row]
return cell
}
The studentProfilePictureResults, studentUsernameResults, and studentNameResults come from arrays of the user's picture, username, and name results pulled from Parse. If a user does not have a profile picture, I get the error, Index is out of range. Obviously, this means that there are, say, three names, three usernames, and only two pictures and Xcode doesn't know how to configure the cell. My question: How can I set a tableView up of a user's username and place their name and profile picture in the same cell, only if they have one?
Trying to store the different attributes in different arrays will be a problem, since as you have found, you end up with problems where a particular user doesn't have an attribute. You could use an array of optionals, so that you could store nil for an absent attribute, but it is much simpler to store the PFObject itself in a single array and accessing the attributes in cellForRowAtIndexPath rather than splitting out the attributes.
Since fetching the photo requires a separate, asynchronous, operation, you can store it separately. Rather than using an array to store the retrieved photos, which would have the same problem of ordering, you can use a dictionary, indexed by the user id; although for a large number of students it would probably be more efficient to use something like SDWebImage to download the photos as required in cellForRowAtIndexPath.
// these are instance properties defined at the top of your class
var students: [PFObject]?
var studentPhotos=[String:UIImage]()
// This is in your fetch function
let studentsQuery = PFUser.Query()
studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject])
let query2 = PFQuery.orQueryWithSubqueries([studentsQuery])
query2.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
guard (error == nil) else {
print(error)
spinningActivity.hideAnimated(true)
return
}
if let results = results {
self.students = results
for object in results {
if let studentProfilePictureFile = object.objectForKey("profile_picture") as? PFFile {
studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in
guard (error != nil) else {
print("Can't get profile picture: \(error)")
return
}
if let studentProfilePicture = UIImage(data: image!) {
self.studentPhotos[object["username"]!]=studentProfilePicture
}
}
}
spinningActivity.hideAnimated(true)
self.tableview.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.students != nil {
return self.students!.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell
cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width / 2
cell.studentProfilePictureImageView.clipsToBounds = true
let student = self.students[indexPath.row]
if let studentPhoto = self.studentPhotos[student["username"]!] {
cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row]
} else {
cell.studentProfilePictureImageView.image = nil
}
cell.studentUsernameLabel.text = student["username"]!
if let fullName = student["full_name"] {
cell.studentNameLabel.text = fullName
} else {
cell.studentNameLabel.text = ""
return cell
}
A few other pointers;
The use of _ to separate words in field names isn't really used in the iOS world; camelCase is preferred, so fullName rather than full_name
It looks like your Parse query could be more efficient if you had a class field or reference object so that you didn't need to supply an array of other class members.
I'm currently in the process of creating an app to display the latest football scores. I've connected to an API through a URL and pulled back the team names for the english premier league into an array of strings.
The problem seems to come from populating the iOS table view that I intend to display the list of teams with. The data appears to be pulled from the API fine, but for some reason the TableView method which creates a cell and returns it doesn't seem to be called. The only time I can get the method to be called is when I actually hard code a value into the array of team names.
Here is my code:
class Main: UIViewController {
var names = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let URL_String = "https://football-api.com/api/?Action=standings&APIKey=[API_KEY_REMOVED]&comp_id=1204"
let url = NSURL(string: URL_String)
let urlRequest = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if let teams = json["teams"] as? [[String : AnyObject]] {
for team in teams {
if let name = team["stand_team_name"] as? String {
self.names.append(name)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}
})
task.resume()
}
// Number of Sections In Table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// Number of Rows in each Section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
// Sets the content of each cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
}
Just wondering if anyone can point me in the right direction here. This code doesn't crash or throw any errors, it just refuses to load a table view. The only reason I can possibly think of is that the array of team names is empty after completing a request to the API. However I've set breakpoints throughout and checked the values of local variables and the desired information is being pulled from the API as intended...
you are in the correct way , just refresh the table using reloadData once you got the new data from API
if let teams = json["teams"] as? [[String : AnyObject]] {
for team in teams {
if let name = team["stand_team_name"] as? String {
self.names.append(name)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.yourtableViewname.reloadData()
})
}
I have a pretty elaborate problem and I think someone with extensive async knowledge may be able to help me.
I have a collectionView that is populated with "Picture" objects. These objects are created from a custom class and then again, these objects are populated with data fetched from Parse (from PFObject).
First, query Parse
func queryParseForPictures() {
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, err: NSError?) -> Void in
if err == nil {
print("Success!")
for object in objects! {
let picture = Picture(hashtag: "", views: 0, image: UIImage(named: "default")!)
picture.updatePictureWithParse(object)
self.pictures.insert(picture, atIndex: 0)
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.filtered = self.pictures
self.sortByViews()
self.collectionView.reloadData()
}
}
}
}
Now I also get a PFFile inside the PFObject, but seeing as turning that PFFile into NSData is also an async call (sync would block the whole thing..), I can't figure out how to load it properly. The function "picture.updatePictureWithParse(PFObject)" updates everything else except for the UIImage, because the other values are basic Strings etc. If I would also get the NSData from PFFile within this function, the "collectionView.reloadData()" would fire off before the pictures have been loaded and I will end up with a bunch of pictures without images. Unless I force reload after or whatever. So, I store the PFFile in the object for future use within the updatePictureWithParse. Here's the super simple function from inside the Picture class:
func updateViewsInParse() {
let query = PFQuery(className: Constants.ParsePictureClassName)
query.getObjectInBackgroundWithId(parseObjectID) { (object: PFObject?, err: NSError?) -> Void in
if err == nil {
if let object = object as PFObject? {
object.incrementKey("views")
object.saveInBackground()
}
} else {
print(err?.description)
}
}
}
To get the images in semi-decently I have implemented the loading of the images within the cellForItemAtIndexPath, but this is horrible. It's fine for the first 10 or whatever, but as I scroll down the view it lags a lot as it has to fetch the next cells from Parse. See my implementation below:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.PictureCellIdentifier, forIndexPath: indexPath) as! PictureCell
cell.picture = filtered[indexPath.item]
// see if image already loaded
if !cell.picture.loaded {
cell.loadImage()
}
cell.hashtagLabel.text = "#\(cell.picture.hashtag)"
cell.viewsLabel.text = "\(cell.picture.views) views"
cell.image.image = cell.picture.image
return cell
}
And the actual fetch is inside the cell:
func loadImage() {
if let imageFile = picture.imageData as PFFile? {
image.alpha = 0
imageFile.getDataInBackgroundWithBlock { [unowned self] (imageData: NSData?, err: NSError?) -> Void in
if err == nil {
self.picture.loaded = true
if let imageData = imageData {
let image = UIImage(data: imageData)
self.picture.image = image
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0.35) {
self.image.image = self.picture.image
self.image.alpha = 1
self.layoutIfNeeded()
}
}
}
}
}
}
}
I hope you get a feel of my problem. Having the image fetch inside the cell dequeue thing is pretty gross. Also, if these few snippets doesn't give the full picture, see this github link for the project:
https://github.com/tedcurrent/Anonimg
Thanks all!
/T
Probably a bit late but when loading PFImageView's from the database in a UICollectionView I found this method to be much more efficient, although I'm not entirely sure why. I hope it helps. Use in your cellForItemAtIndexPath in place of your cell.loadImage() function.
if let value = filtered[indexPath.row]["imageColumn"] as? PFFile {
if value.isDataAvailable {
cell.cellImage.file = value //assign the file to the imageView file property
cell.cellImage.loadInBackground() //loads and does the PFFile to PFImageView conversion for you
}
}