get data from firebase children - ios

I have two custom cells in one table view.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
if (indexPath.row == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "Main", for: indexPath) as! PostTableViewCell
//Configure the cell
cell.PostView.layer.cornerRadius = 5
cell.PostView.layer.masksToBounds = false
cell.PostView.layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
cell.PostView.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.PostView.layer.shadowOpacity = 0.9
let post = Comments[indexPath.row] as! [String: AnyObject]
let commentname = post["author"] as? String
sendAuthor = post["author"] as? String
cell.CommentersName.setTitle(commentname, for: .normal)
if let seconds = post["pub_time"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
let formating = timeStampDate as Date
cell.CommentTime.text = dateFormatter.string(from: formating)
}
cell.comment.text = post["content"] as? String
textViewDidChange(cell.comment)
cell.comment.frame.size.width = 344
cell.comment.sizeToFit()
cell.comment.clipsToBounds = true
cell.REply.frame.origin.y = cell.comment.frame.maxY + 10
cell.PostView.frame.size.height = cell.comment.frame.maxY + 50
TableView.rowHeight = cell.PostView.frame.size.height + 20
cell.LikesNumber.text = post["num_likes"] as? String
replyId = post["id"] as? String
cell.checkfornightmode()
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "Reply", for: indexPath) as! RepliesTableViewCell
cell.ReplyCustomCell.layer.cornerRadius = 5
cell.ReplyCustomCell.layer.masksToBounds = false
cell.ReplyCustomCell.layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
cell.ReplyCustomCell.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.ReplyCustomCell.layer.shadowOpacity = 0.9
let post = Comments[indexPath.row] as! [String: AnyObject]
let posttest = post["id"] as? String
let replyRef = Database.database().reference().child("main").child("posts").child(postID!).child("comments").child(posttest!).child("comments")
replyRef.observeSingleEvent(of: .value, with: { (snapshot:DataSnapshot) in
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for testingkey in postsDictionary.keys {
Database.database().reference().child("main").child("posts").child(self.postID!).child("comments").child(posttest!).child("comments").child(testingkey).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let content : String? = value?["content"] as? String ?? ""
cell.ReplyText.text = content!
})
}
}
})
TableView.rowHeight = 150.0
return cell
}
}
The first cell with the identifier main is supposed to print out all the intial comments for a certain post. The second cell with the identifier is supposed to print out the comments to main comments. Based on this code, I am only getting the last comment of the main post and the last comment to the main posts.
This is what the json looks like

First thing is to separate the firebase call into a separate function and in that function populate a dictionary with posts as key and comments as value
for example like this
var postComments: [String: [String]] = [:] // post as key and string array as comments
In firebase database call populate this with snapshot.
After the data call but within the firebase Database call back use this function to reload data
DispatchQueue.main.async{
tableView.reloadData()
}
Set the cell with postComments array.

Related

Multiple collectionviews in one Viewcontroller causes Index out of range error

I try to use three collectionviews in one Viewcontroller. I parse the data like the following method shows:
At the bottom i add the data depending on the position to the right list (this part works)
func getEventData(eventIDs: [String], plz: String, positiona: Int){
for eventId in eventIDs {
let ref = Database.database().reference().child("Events").child(plz).child(eventId)
ref.observe(.value, with: { snapshot in
let item = snapshot.value as? [String: AnyObject]
let eventName = item?["name"] as! String
let date = item?["date"] as! String
let lat = item?["lat"] as! String
let lng = item?["lng"] as! String
let infos = item?["additionalInfos"] as! String
let position = item?["position"] as! String
let ts = item?["ts"] as! Int
let createdBy = item?["createdBy"] as! String
let timestamp = NSDate().timeIntervalSince1970
if (ts > Int(timestamp)) {
let eo = EventObject(eventID: eventId, eventName:
eventName, info: infos, createdBy: createdBy, date: date, lat: lat, lng: lng, position: position, ts: ts)
if positiona == 0{
self.acceptedEvents.append(eo)
self.acceptedEventscv.reloadData()
}else if positiona == 1{
self.myEvents.append(eo)
self.myEventscv.reloadData()
}else if positiona == 2{
self.storedEvents.append(eo)
self.storedEventscv.reloadData()
}
}
})
}
}
In my NumbersofItemsInSection method i did the following which works as well:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.acceptedEventscv{
return acceptedEvents.count
}else if collectionView == self.storedEventscv{
return storedEvents.count
}else if collectionView == self.myEventscv{
return myEvents.count
}else{
return 0
}
}
and in my CellForRowAtItem method i tried the following
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.acceptedEventscv{
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier:
"acceptedEventsCell", for: indexPath) as!
acceptedEventsCollectionViewCell
let eo = acceptedEvents[indexPath.row]
cell.eventName.text = eo.eventName
let items = eo.date!.components(separatedBy: " ")//Here replase
space with your value and result is Array.
//Direct line of code
//let items = "This is my String".components(separatedBy: " ")
let date = items[0]
let time = items[1]
cell.date.text = date
cell.time.text = time
getUserNameAge(label: cell.usernameAge)
return cell
}else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "savedEventsCell", for: indexPath) as! savedEventsCollectionViewCell
let eo = acceptedEvents[indexPath.row]
cell.eventName.text = eo.eventName
let items = eo.date!.components(separatedBy: " ")//Here replase space with your value and result is Array.
//Direct line of code
//let items = "This is my String".components(separatedBy: " ")
let date = items[0]
let time = items[1]
cell.date.text = date
cell.time.text = time
getUserNameAge(label: cell.usernameAge)
return cell
}
}
The problem is if i have more items in the seccond CollectionView, i always get this error:
Thread 1: Fatal error: Index out of range
at this line of code:
let eo = acceptedEvents[indexPath.row]
cellForItemAt also must be like
if collectionView == self.acceptedEventscv{
let item = acceptedEvents[indexPath.row]
----
return cell
}else if collectionView == self.storedEventscv{
let item = storedEvents[indexPath.row]
----
return cell
}else {
let item = myEvents[indexPath.row]
----
return cell
}
what happens now in your case is that you access the same array acceptedEvents in both cases where the returned count in numberOfItemsInSection may be different

how to organize tableview cells

I have two different kinds of tableview cells in one table view. The first cell prints out original comments to a post, the second cell prints out comments to another comment. Currently, the tableview prints out all the correct cells in no particular order. However, I want to print the cells in a particular order. I want the cells that contain comments to another comment to appear below the comment it is being commented on.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCell(withIdentifier: "Main", for: indexPath) as! PostTableViewCell
//Configure the cell
cell.PostView.layer.cornerRadius = 5
cell.PostView.layer.masksToBounds = false
cell.PostView.layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
cell.PostView.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.PostView.layer.shadowOpacity = 0.9
let post = Comments[indexPath.row] as! [String: AnyObject]
let commentname = post["author"] as? String
sendAuthor = post["author"] as? String
cell.CommentersName.setTitle(commentname, for: .normal)
if let seconds = post["pub_time"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
let formating = timeStampDate as Date
cell.CommentTime.text = dateFormatter.string(from: formating)
}
cell.comment.text = post["content"] as? String
textViewDidChange(cell.comment)
cell.comment.frame.size.width = 344
cell.comment.sizeToFit()
cell.comment.clipsToBounds = true
cell.REply.frame.origin.y = cell.comment.frame.maxY + 10
cell.report.frame.origin.y = cell.comment.frame.maxY + 10
cell.Likes.frame.origin.y = cell.comment.frame.maxY + 10
cell.LikesNumber.frame.origin.y = cell.comment.frame.maxY + 10
cell.PostView.frame.size.height = cell.comment.frame.maxY + 50
TableView.rowHeight = cell.PostView.frame.size.height + 20
cell.CommentersName.sizeToFit()
cell.pole.frame.origin.x = cell.CommentersName.frame.maxX + 5
cell.CommentTime.frame.origin.x = cell.pole.frame.maxX + 5
let numLikes = post["num_likes"] as? NSNumber
cell.LikesNumber.text = String(describing: numLikes!)
replyId = post["id"] as? String
let replyTo = post["reply_to"] as? String
let postID = post["post_id"] as? String
if replyTo == postID {
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "Reply", for: indexPath) as! RepliesTableViewCell
cell.ReplyCustomCell.layer.cornerRadius = 5
cell.ReplyCustomCell.layer.masksToBounds = false
cell.ReplyCustomCell.layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
cell.ReplyCustomCell.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.ReplyCustomCell.layer.shadowOpacity = 0.9
let post = Comments[indexPath.row] as! [String: AnyObject]
cell.ReplyText.text = post["content"] as? String
let commentname = post["author"] as? String
cell.author.setTitle(commentname, for: .normal)
if let seconds = post["pub_time"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
let formating = timeStampDate as Date
cell.time.text = dateFormatter.string(from: formating)
}
let numLikes = post["num_likes"] as? NSNumber
cell.num_likes.text = String(describing: numLikes!)
textViewDidChange(cell.ReplyText)
cell.ReplyText.frame.size.width = 232
cell.ReplyText.sizeToFit()
cell.ReplyText.clipsToBounds = true
cell.author.sizeToFit()
cell.pole.frame.origin.x = cell.author.frame.maxX + 5
cell.time.frame.origin.x = cell.pole.frame.maxX + 5
cell.Likes.frame.origin.y = cell.ReplyText.frame.maxY + 10
cell.num_likes.frame.origin.y = cell.ReplyText.frame.maxY + 10
cell.reportButton.frame.origin.y = cell.ReplyText.frame.maxY + 10
cell.replyButton.frame.origin.y = cell.ReplyText.frame.maxY + 10
cell.ReplyCustomCell.frame.size.height = cell.ReplyText.frame.maxY + 50
TableView.rowHeight = cell.ReplyCustomCell.frame.size.height + 20
return cell
}
cell.checkfornightmode()
return cell
}
The comments that are associated with each other have the same "id", how will I organize the cells so that the comments of a main comment will be listed under the original comment. Thank you
You can create one Comment custom object class which will hold an array of sub comments and the main comment to arrange or manage your data structure properly. After that you can use it properly with your table view cell.
Okay so for example you can have the below data structure.
Create one Comment class:
class Comment {
comment_id
content
post_id
reply_to
}
Now create one more class for your table view:
class CommentTableDataModel {
var mainComment: Comment // Of type Comment class
var replies: [Comment] // Array of type Comment class for sub comments
}
So now just iterate through your firebase Comments array and prepare an array list of type 'CommentTableDataModel' objects as a datasource for your table. So finally you will have an array of type object 'CommentTableDataModel' and each object of type 'CommentTableDataModel' contains the main comment info as well as the list of replies info with that, with this you can manage your data.

Having issue in reuseable cell in UITableView cell

I have two kinds of design in single UITableViewCell. Here is the design which I want and getting at the time of loading viewController
But after scrolling I'm getting following result.
I think this problem is caused by reusability of UITableViewCell. here is my code of cellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "notificationCell", for: indexPath) as! NotificationTableViewCell
cell.selectionStyle = .none
cell.btnClose.tag = indexPath.row
let noti_flag = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "noti_flag") //as! String
let noti_flag_string = NSString(format: "%#", noti_flag as! CVarArg) as String
cell.lbl_From.text = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "caller_id") as? String ?? ""
if noti_flag_string == "0" {
cell.lblTime.isHidden = true
cell.imgThumbIcon.isHidden = true
cell.lbl_remaining.isHidden = true
cell.lbl_mm_text.text = "Missed call"
cell.lbl_mm_text.font = cell.lbl_mm_text.font.withSize(23)
}
else{
var startAttributedText = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "rebound_start_time") as! String
var endAttributedText = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "rebound_end_time") as! String
startAttributedText = Model.shared.convertLocalTimeToServer(timeString: startAttributedText,isTimeFromServer: true)
endAttributedText = Model.shared.convertLocalTimeToServer(timeString: endAttributedText,isTimeFromServer: true)
let dateString:String = startAttributedText + " - " + endAttributedText
cell.lblTime.attributedText = convertStringToAttr(dateString: dateString)
cell.lbl_remaining.text = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "remaining_time") as? String ?? ""
cell.lbl_mm_text.text = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "mm_text") as? String ?? ""
//cell.lbl_From.text = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "caller_id") as? String ?? ""
let mm_type = (arrayNotificationList.object(at: indexPath.row) as! NSDictionary).object(forKey: "mm_type") as! String//"img"
switch mm_type {
case "img":
cell.imgThumbIcon.image = UIImage(named: "thumb_camera")
case "vid":
cell.imgThumbIcon.image = UIImage(named: "thumb_video")
case "aud":
cell.imgThumbIcon.image = UIImage(named: "thumb_audio")
case "str":
cell.imgThumbIcon.image = UIImage(named: "thumb_sticker")
case "txt":
cell.imgThumbIcon.image = UIImage(named: "thumb_text")
case "brd":
cell.imgThumbIcon.image = UIImage(named: "thumb_brand")
default:
cell.imgThumbIcon.image = UIImage(named: "thumb_camera")
}
}
return cell
}
So please help me to solve this issue. Thanks in Advance.
The problem is that when you scrolled, the
cell.lblTime.isHidden = true
line hid the label in the cell. When it was reused, it was still hidden so the middle label enlarged to fill up the remaining space.
The solution is to either,
A. Create another cell subclass which cleans up the code considerably and it would no longer be necessary to show or hide labels.
B. Make sure to set
cell.lblTime.isHidden = false
in the else clause.
I hope this helps.

How to filter an array of JSON objects to be used in a table view?

I'm getting JSON data from an API and parsing that data in objects, which are then simply stored in an array of objects. The objects themselves contain data about articles from a newspaper. However, I need to filter that data. Some of the objects I'm getting from my JSON actually have no article content because they are pictures and not articles (i.e. some of the "nodes" from the API's JSON have content that I don't want to see in my table view).
In my JSON-parsing function, I've tried to make it so that the parsed object will only get added to the array of parsed objects if the character count of the "articleContent" variable is above 40. Here is what it looked like.
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
}
However, this simply does not work. I get the typical "unexpectedly found nil while unwrapping an Optional value" error message (I don't get a specific line for the error). How can I make this work ? I'm essentially trying to prevent the array from having objects with empty articleContent, because then that screws up my table view (empty cells, duplicates, etc...).
Here is my cellForRowAtIndexPath code, and my JSON-parsing code:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let row = indexPath.row
guard let cell = tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as? CurrentIssueArticlesTableViewCell else {
print ("error: currentIssueTableView cell is not of class CurrentIssueArticlesTableViewCell, we will use EditorialsTableViewCell instead")
return tableView.dequeueReusableCellWithIdentifier(CurrentIssueArticlesTableCellIdentifier, forIndexPath: indexPath) as! EditorialsTableViewCell
}
let currentIssueObject = currentIssueObjects.objectAtIndex(indexPath.row) as! IssueElement
let title = currentIssueObject.title ?? ""
let timeStampDateObject = NSDate(timeIntervalSince1970: NSTimeInterval(currentIssueObject.timeStamp))
let timeStampDateString = dateFormatter.stringFromDate(timeStampDateObject) ?? "Date unknown"
if let author = currentIssueObject.author {
cell.currentIssueArticlesAuthorLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesAuthorLabel!.text = author
}
let issueNumber = currentIssueObject.issueNumber ?? ""
let volumeNumber = currentIssueObject.volumeNumber ?? ""
let articleContent = currentIssueObject.articleContent ?? ""
let nodeID = currentIssueObject.nodeID ?? 0
cell.currentIssueArticlesHeadlineLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.currentIssueArticlesHeadlineLabel.text = title
cell.currentIssueArticlesPublishDateLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
cell.currentIssueArticlesPublishDateLabel.text = timeStampDateString
if row == 0 {
cell.userInteractionEnabled = false
let imageURL = (currentIssueObjects.objectAtIndex(row) as! IssueElement).imageURL
cell.currentIssueArticlesHeadlineLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesAuthorLabel.textColor = UIColor.clearColor()
cell.currentIssueArticlesPublishDateLabel.textColor = UIColor.clearColor()
cell.request?.cancel()
if let image = self.imageCache.objectForKey(imageURL!) as? UIImage {
cell.currentIssueArticlesBackgroundImageView.image = image
} else {
cell.currentIssueArticlesBackgroundImageView.image = UIImage(named: "reveal Image")
cell.request = Alamofire.request(.GET, imageURL!).responseImage() { response in
if response.result.error == nil && response.result.value != nil {
self.imageCache.setObject(response.result.value!, forKey: response.request!.URLString)
cell.currentIssueArticlesBackgroundImageView.image = response.result.value
} else {
}
}
}
cell.currentIssueArticlesBackgroundImageView.hidden = false
}
else {
cell.currentIssueArticlesBackgroundImageView.hidden = true
}
return cell
}
JSON-parsing code:
func populateCurrentIssue() {
if populatingCurrentIssue {
return
}
populatingCurrentIssue = true
self.cellLoadingIndicator.backgroundColor = goldenWordsYellow
self.cellLoadingIndicator.startAnimating()
Alamofire.request(GWNetworking.Router.Issue).responseJSON() { response in
if let JSON = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
var nodeIDArray : [Int]
if (JSON .isKindOfClass(NSDictionary)) {
for node in JSON as! Dictionary<String, AnyObject> {
let nodeIDValue = node.0
var lastItem : Int = 0
self.nodeIDArray.addObject(nodeIDValue)
if let issueElement : IssueElement = IssueElement(title: "Could not retrieve title", nodeID: 0, timeStamp: 0, imageURL: "init", author: "Author not found", issueNumber: "Issue # error", volumeNumber: "Volume # error", articleContent: "Could not retrieve article content", coverImageInteger: "init", coverImage: UIImage()) {
issueElement.title = node.1["title"] as! String
issueElement.nodeID = Int(nodeIDValue)!
let timeStampString = node.1["revision_timestamp"] as! String
issueElement.timeStamp = Int(timeStampString)!
issueElement.imageURL = String(node.1["image_url"])
if let author = node.1["author"] as? String {
issueElement.author = author
}
if let issueNumber = node.1["issue_int"] as? String {
issueElement.issueNumber = issueNumber
}
if let volumeNumber = node.1["volume_int"] as? String {
issueElement.volumeNumber = volumeNumber
}
if let articleContent = node.1["html_content"] as? String {
issueElement.articleContent = articleContent
}
issueElement.coverImageInteger = String(node.1["cover_image"]) // addition specific to the Current Issue View Controller
lastItem = self.currentIssueObjects.count
print(issueElement.nodeID)
if issueElement.articleContent.characters.count > 40 {
self.currentIssueObjects.addObject(issueElement)
print(issueElement.nodeID)
}
// Sorting with decreasing timestamp from top to bottom.
let timestampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([timestampSortDescriptor])
// Placing the object with coverImage
let coverImageSortDescriptor = NSSortDescriptor(key: "coverImageInteger", ascending: false)
self.currentIssueObjects.sortUsingDescriptors([coverImageSortDescriptor])
let indexPaths = (lastItem..<self.currentIssueObjects.count).map {
NSIndexPath(forItem: $0, inSection: 0) }
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.currentIssueTableView.reloadData()
self.cellLoadingIndicator.stopAnimating()
self.cellLoadingIndicator.hidesWhenStopped = true
}
}
}
self.populatingCurrentIssue = false
}
}

Firebase function freezes app in xcode7, but works in xcode6.4

For some reason this code works perfectly in xcode6.4, but when switching to xcode7 it freezes the app.
What I am trying to do is pull the post information on a user's feed and display it on a tableview. I am able to pull the information from Firebase, but the app freezes before it displays on the tableview.
EDIT: The tableview works when I do not have any constraints or autolayout. It seems to not work when I try to have dynamic cell heights.
func getRadarData() {
let url = "https://(insert appname).firebaseio.com/users/" + currentUser + "/postsReceived/"
let targetRef = Firebase(url: url)
targetRef.observeEventType(.ChildAdded, withBlock: {
snapshot in
print("child")
if let found = self.posts.map({ $0.key }).indexOf(snapshot.key) {
let obj = self.posts[found]
print(obj)
print(found)
self.posts.removeAtIndex(found)
}
let postsUrl = "https://(insert appname).firebaseio.com/posts/" + snapshot.key
let postsRef = Firebase(url: postsUrl)
var updatedAt = snapshot.value["updatedAt"] as? NSTimeInterval
var endAt = snapshot.value["endAt"] as? NSTimeInterval
if updatedAt == nil {
updatedAt = 0
}
if endAt == nil {
endAt = 0
}
postsRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let key = snapshot.key
{if let content = snapshot.value["content"] as? String {
if let creator = snapshot.value["creator"] as? String {
if let createdAt = snapshot.value["createdAt"] as? NSTimeInterval {
let userurl = "https://(insert appname).firebaseio.com/users/" + (creator)
let userRef = Firebase(url: userurl)
userRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let username = snapshot.value["username"] as? String {
let updatedDate = NSDate(timeIntervalSince1970: (updatedAt!/1000))
let createdDate = NSDate(timeIntervalSince1970: (createdAt/1000))
let endedDate = NSDate(timeIntervalSince1970: (endAt!))
let post = Post(content: content, creator: creator, key: key, createdAt: updatedDate, name: username, joined: true, messageCount: 0, endAt: endedDate)
self.posts.append(post)
// Sort posts in descending order
self.posts.sortInPlace({ $0.createdAt.compare($1.createdAt) == .OrderedDescending })
self.tableView.reloadData()
}
})
}
}
}
}
})
})
}
Here is my code for my tableview where I used autolayout on the textView and nameLabel
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: RadarTableViewCell = tableView.dequeueReusableCellWithIdentifier("radarCell", forIndexPath: indexPath) as! RadarTableViewCell
let creator: (String) = posts[indexPath.row].creator
let key = posts[indexPath.row].key
let radarContent: (AnyObject) = posts[indexPath.row].content
cell.textView.selectable = false
cell.textView.text = radarContent as? String
cell.textView.userInteractionEnabled = false
cell.textView.selectable = true
let radarCreator: (AnyObject) = posts[indexPath.row].name
cell.nameLabel.text = radarCreator as? String
return cell
The issue was that I had initial text in my textView. I deleted it on my Storyboard and my app works now.
Found the solution here: Why does a previously working Xcode project hang up in Xcode 7 when presenting a new UITableviewController Subclass?

Resources