updating values in a realm database swift - ios

I am trying to update the values on a realm database. If a user selects a row containing values I want to be able to update the values of that row. Here is my code but instead of updating, it creates another value in the database
func updateTodoList(todoList: TodoListModel, name: String, description: String, createdDate: Date, remiderDate: Date, photo: Data, isCompleted: Bool) -> Void {
try! database.write {
if name != "" {
todoList.name = name
} else {
todoList.name = "No extra information"
}
todoList.desc = description
todoList.createdDate = createdDate
todoList.remiderDate = remiderDate
todoList.photo = photo
todoList.isCompleted = false
}
}
my did select row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let todoList = todoItems?[indexPath.row]
let storyBoard: UIStoryboard = UIStoryboard(name: "AddTodoListSB", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: Constants.ADD_TODO_SB) as! AddTodoListVC
newViewController.loadViewIfNeeded()
let min = Date()
let max = Date().addingTimeInterval(60 * 60 * 60 * 60)
guard let itemPhoto = UIImagePNGRepresentation(newViewController.imageView.image!) else {return}
newViewController.picker.minimumDate = min
newViewController.picker.maximumDate = max
// newViewController.showDateTimePicker(sender: <#T##AnyObject#>)
newViewController.picker.completionHandler = { date in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.title = formatter.string(from: date)
let reminder = formatter.string(from: date)
TodoListFunctions.instance.updateTodoList(todoList: todoList!, name: newViewController.titleTxtField.text!, description: newViewController.moreInfoTxtView.text!, createdDate: (todoList?.createdDate)!, remiderDate: formatter.date(from: reminder)!, photo: itemPhoto, isCompleted: false)
}
tableView.reloadData()
self.present(newViewController, animated: true, completion: nil)
}
// TodolistModel
class TodoListModel: Object {
#objc dynamic var id = UUID().uuidString
#objc dynamic var name: String = ""
#objc dynamic var desc: String = "No Description"
#objc dynamic var photo: Data? = nil
#objc dynamic var createdDate: Date?
#objc dynamic var remiderDate: Date?
#objc dynamic var isCompleted = false
override static func primaryKey() -> String? {
return "id"
}
let parentCategory = LinkingObjects(fromType: CategoryModel.self, property: "items")
}
further codes would be supplied on request

To update an object it must have a primary key and after you edit it use
// if it doesn't exist it'll be added
database.add(editedObjc, update: true)
//
// create object 1 , note: r = database
let lista = TaskList()
lista.pid = 1
lista.name = "Whole List"
// create object 2
let lista2 = TaskList()
lista2.pid = 2
lista2.name = "Whole List 2"
// add to database by write
r.add([lista,lista2])
let stored = r.objects(TaskList.self)
print("before edit" , stored)
// edit name of object 2
lista2.name = "qqwwqwqwqwqwqwqwq"
// update the object after changing it's name
r.add(lista2, update: true)
let stored2 = r.objects(TaskList.self)
print("after edit" , stored2)

Related

add the values according to appending the values

How to add the values according to appending the values in swift3.
this is my datasource:-
class QM_ChartDataSourceModel: NSObject {
var dataListArray:Array<QM_CartModel>? = []
init(array :Array<[String:Any]>?) {
super.init()
var newArray:Array<[String:Any]> = []
if array == nil{
newArray = self.getJsonDataStored22()
}
else{
newArray = array!
}
var datalist:Array<QM_CartModel> = []
for dict in newArray{
let model = QM_CartModel(dictionary: dict)
datalist.append(model!)
}
self.dataListArray = datalist
}
}
typealias dummyDataSource22 = QM_ChartDataSourceModel
extension dummyDataSource22{
func getJsonDataStored22() ->Array<Dictionary<String,String>>{
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]] as Array<Dictionary<String,String>>
return jsonArray
}
}
in tableviewcell:
func setEventData(carts:QM_CartModel)
{
self.name.text = carts.cartname
self.price.text = carts.cartsum
self.itemQuantityStepper.value = 1
setItemQuantity(quantity)
print(self.price.text)
let value = carts.cartsum
let x: Int? = Int(value!)
print(x)
let add = x!
print(add)
let theIntegerValue1 :Int = add
let theStringValue1 :String = String(theIntegerValue1)
self.price.text = theStringValue1
}
my model:-
class QM_CartModel: NSObject {
var cartname :String!
var cartprice:String!
var cartquantity:String!
var carttotalprice:String!
var carttotal:String!
var cartQR:String!
var cartvalue:String!
var cartsum:String?
var cartid:String!
init?(dictionary :JSONDictionary) {
guard let name = dictionary["name"] as? String else {
return
}
if let quantity = dictionary["quantity"] as? String{
let price = dictionary["price"] as? String
let id = dictionary["id"] as? String
self.cartid = id
self.cartprice = price
self.cartquantity = quantity
let fullNameArr = price?.components(separatedBy: " ")
let QR = fullNameArr?[0]
let value = fullNameArr?[1]
self.cartQR = QR
self.cartvalue = value
let x: Int? = Int(value!)
print(x)
let y:Int? = Int(quantity)
print(y)
let sum = x! * y!
print(sum)
let sum1 = String(describing: sum)
cartsum = sum1
}
my viewmodel:-
class QM_ChartViewModel: NSObject {
var datasourceModel:QM_ChartDataSourceModel
var insertedArray:QM_CartModel?
var filteredListArray:Array<QM_CartModel>? = []
var totalListArray:Array<QM_CartModel>? = []
init(withdatasource newDatasourceModel: QM_ChartDataSourceModel) {
datasourceModel = newDatasourceModel
print(datasourceModel.dataListArray)
}
func datafordisplay(atindex indexPath: IndexPath) -> QM_CartModel{
return datasourceModel.dataListArray![indexPath.row]
}
func numberOfRowsInSection(section:Int) -> Int {
return datasourceModel.dataListArray!.count
}
func delete(atIndex indexPath: IndexPath) {
datasourceModel.dataListArray!.remove(at: indexPath.row)
}
func search(idsearch :String?) {
filteredListArray = datasourceModel.dataListArray?.filter{($0.cartid?.range(of: idsearch!, options: .caseInsensitive) != nil)}
print(filteredListArray)
}
func searchindex(objectatindex index: Int) -> QM_CartModel {
return self.filteredListArray![index]
}
func total()
{ totalListArray = datasourceModel.dataListArray?.filter{($0.cartsum != nil)}
print(totalListArray)
}
func add(){
datasourceModel.dataListArray?.append(insertedArray!)
print(datasourceModel.dataListArray)
print(insertedArray?.offerAddName)
print(insertedArray?.offerprice)
self.datasourceModel.dataListArray = datasourceModel.dataListArray
print(insertedArray?.cartsum)
}
func addquantity(quantity:Int)
{
// datasourceModel.dataListArray?.filter{ $0.cartid! == cartaddedid! }.first?.qty = quantity as NSNumber?
}
}
in viewcontroller my code as below:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chartViewModel.numberOfRowsInSection(section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell: QM_ChartCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
if cell == nil {
tableView.register(UINib(nibName: "QM_ChartCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? QM_ChartCell
}
cell.setEventData(carts: chartViewModel.datafordisplay(atindex: indexPath))
print(cell.numbers)
see here can see the total.So that way i need to display the total
this is my code ...here i getting the values model.cartsum.So this value is appending in var number:[String] = []
.But here i need-as values are appending ,here i need to add the number.So first value is 1 and second value is 2 then i need to add this values.And if next number is 3 then i need to get sum = 6.
How to get
You need to calculate all the cart stuff just after you get it either from service or from local. You don't need to do calculation in cellForRowAtIndex: method because it should be done once.
I assume this is your data structure as mentioned in question.
let jsonArray = [["id":"311","name":"Dosa Fest","price":"QR 40","quantity":"3"],
["id":"312","name":"Organic Vegan Fest","price":"QR 40","quantity":"2"],
["id":"313","name":"Food Of Life Time","price":"QR 56","quantity":"7"],
["id":"314","name":"Tea Time","price":"QR 88","quantity":"1"],
["id":"315","name":"Dosa Fest","price":"QR 13","quantity":"6"],
["id":"316","name":"Organic Vegan Fest","price":"QR 4","quantity":"8"],
["id":"317","name":"Food Of Life Time","price":"QR 90","quantity":"3"],
["id":"318","name":"Tea Time","price":"QR 66","quantity":"2"],
["id":"319","name":"Dosa Fest","price":"QR 81","quantity":"6"],
["id":"320","name":"Organic Vegan Fest","price":"QR 49","quantity":"2"]]
Here is how to calculate the total of the cart. As per your data considering price is in Int
var total = 0
for item in jsonArray {
/// Will check if quantity is available in dictionary and convertible into an Int else will be 0
let quantity = Int(item["quantity"] ?? "0") ?? 0
/// Will check price key exists in the dictionary
if let priceStr = item["price"] {
/// Will fetch the last components and check if it is convertible into an Int else 0
let price = Int(priceStr.components(separatedBy: " ").last ?? "0") ?? 0
/// Multiply price with quantity and add into total
total += price * quantity
}
}
print(total)
Output: 1776
Another way:
let total = jsonArray.map { (item) -> Int in
let quantity = Int(item["quantity"] ?? "0") ?? 0
let price = Int(item["price"]?.components(separatedBy: " ").last ?? "0") ?? 0
return quantity * price
}.reduce(0, +)
print(total)
Please try this code if you have array of Int
var arrayOfInt = [2,3,4,5,4,7,2]
let reducedNumberSum = arrayOfInt.reduce(0,+)
print(reducedNumberSum)
Answer: 27
In your code
let model = chartViewModel.datafordisplay(atindex: indexPath)
Please describe more so we can answer according your problem.

Get items from array by the nearest day

I'm adding items to my Firebase with date in this format:
var date: NSDate?
override func viewDidLoad() {
super.viewDidLoad()
date = NSDate()
}
// ......
#IBAction func save(_ sender: UIBarButtonItem) {
if let realDate = date {
fullDate = "\(String(describing: realDate))"
}
// ......
let wordItem = Word(word: word, translation: translation, date: fullDate, fullDate: trueDate, exOne: exOne, exTwo: exTwo, completed: false, keyRandom: randomString)
let wordItemRef = self.ref?.child("Users").child(uid).child("LearnedWords").child(randomString)
wordItemRef?.setValue(wordItem.toAnyObject())
presentingViewController?.dismiss(animated: true, completion: nil)
}
So, my Firebase for Date looks like this:
Then, I retrieve this data in another ViewController and add it to the array:
override func viewDidLoad() {
super.viewDidLoad()
// checking if user is in
guard let uid = Auth.auth().currentUser?.uid else {
return
}
// retrieving data from FireBase
ref = Database.database().reference()
databaseHandle = ref?.child("Users").child(uid).child("LearnedWords").observe(.value, with: { (snapshot) in
var newItems: [Word] = []
for item in snapshot.children {
let wordItem = Word(snapshot: item as! DataSnapshot)
newItems.append(wordItem)
}
newItems.sort(by: { $0.date.compare($1.date) == .orderedDescending})
self.words = newItems
self.getAllMessagesSent(snapshot: newItems)
})
}
// retrieve data from Firebase to the View
func getAllMessagesSent(snapshot: [Word]) {
int = snapshot.count - 1
array = snapshot
}
The question:
How is it possible to retrieve the items from array from the nearest day? If today is 16 of August, I should get all items of the nearest day (for example, 8 items from 12 of August, if this date was the last). And should I change the way I'm adding date to Firebase to achieve this?
Edit
I achieved this by comparing the last date in the array with all other dates:
// retrieve data from Firebase to the View
var dateToCompare: String?
var array: [Word] = []
func getAllMessagesSent(snapshot: [Word]) {
int = snapshot.count - 1
array = snapshot
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
// get the nearest item's date and convert it to Date
dateToCompare = array[0].fullDate
let formattedDateToCompare = dateFormatter.date(from: dateToCompare!)
// make array of dates
var dateArray = [NSDate]()
var numberOfWordsThisDay = 1
// formatting all dates in the array
for i in 0..<array.count {
let date1 = dateFormatter.date(from: array[i].fullDate)
dateArray.append(date1! as NSDate)
}
// comparing and in case of cussces increase the number
for i in 1..<array.count {
if Calendar.current.compare(formattedDateToCompare!, to: dateArray[i] as Date, toGranularity: .day) == .orderedSame {
numberOfWordsThisDay += 1
}
}
self.numOfWords.placeholder = "From \(numberOfWordsThisDay) to \(array.count)"
}
It works, but it definitely doesn't look like efficient solution, because I loop over two huge arrays. Is it possible to improve my code? Thanks!

Test fails when asserting dates

I am trying to verify that two items I am storing are the same. However, while testing I am getting an error when checking a Date property.
Note: my Item class implements the Equatable protocol.
This is my setUp method:
class InputViewControllerTests: XCTestCase {
var sut: InputViewController!
var placemark: MockPlacemark!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main",
bundle: nil)
sut = storyboard
.instantiateViewController(
withIdentifier: "InputViewController")
as! InputViewController
_ = sut.view
}
}
This is the extension of my test class:
extension InputViewControllerTests {
class MockGeocoder: CLGeocoder {
var completionHandler: CLGeocodeCompletionHandler?
override func geocodeAddressString(
_ addressString: String,
completionHandler: #escaping CLGeocodeCompletionHandler) {
self.completionHandler = completionHandler
}
}
class MockPlacemark : CLPlacemark {
var mockCoordinate: CLLocationCoordinate2D?
override var location: CLLocation? {
guard let coordinate = mockCoordinate else
{ return CLLocation() }
return CLLocation(latitude: coordinate.latitude,
longitude: coordinate.longitude)
}
}
}
This is my test:
func test_Save_UsesGeocoderToGetCoordinateFromAddress() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let timestamp = 1456095600.0
let date = Date(timeIntervalSince1970: timestamp)
sut.titleTextField.text = "Foo"
sut.dateTextField.text = dateFormatter.string(from: date)
sut.locationTextField.text = "Bar"
sut.addressTextField.text = "Infinite Loop 1, Cupertino"
sut.descriptionTextField.text = "Baz"
let mockGeocoder = MockGeocoder()
sut.geocoder = mockGeocoder
sut.itemManager = ItemManager()
sut.save()
placemark = MockPlacemark()
let coordinate = CLLocationCoordinate2DMake(37.3316851,
-122.0300674)
placemark.mockCoordinate = coordinate
mockGeocoder.completionHandler?([placemark], nil)
let item = sut.itemManager?.item(at: 0)
let testItem = ToDoItem(title: "Foo",
itemDescription: "Baz",
timestamp: timestamp,
location: Location(name: "Bar",
coordinate: coordinate))
XCTAssertEqual(item, testItem)
}
This is the implementation of the save() method:
class InputViewController: UIViewController {
// ...
#IBAction func save() {
guard let titleString = titleTextField.text,
titleString.characters.count > 0 else { return }
let date: Date?
if let dateText = self.dateTextField.text,
dateText.characters.count > 0 {
date = dateFormatter.date(from: dateText)
} else {
date = nil
}
let descriptionString = descriptionTextField.text
if let locationName = locationTextField.text,
locationName.characters.count > 0 {
if let address = addressTextField.text,
address.characters.count > 0 {
geocoder.geocodeAddressString(address) {
[unowned self] (placeMarks, error) -> Void in
let placeMark = placeMarks?.first
let item = ToDoItem(
title: titleString,
itemDescription: descriptionString,
timestamp: date?.timeIntervalSince1970,
location: Location(
name: locationName,
coordinate: placeMark?.location?.coordinate))
self.itemManager?.add(item)
}
}
}
}
}
I am having trouble trying to figure out what is wrong with this. The error I am getting is:
test_Save_UsesGeocoderToGetCoordinateFromAddress()] failed: XCTAssertEqual failed: ("Optional(ToDo.ToDoItem(title: "Foo", itemDescription: Optional("Baz"), timestamp: Optional(1456030800.0), location: Optional(ToDo.Location(name: "Bar", coordinate: Optional(__C.CLLocationCoordinate2D(latitude: 37.331685100000001, longitude: -122.03006739999999))))))") is not equal to ("Optional(ToDo.ToDoItem(title: "Foo", itemDescription: Optional("Baz"), timestamp: Optional(1456095600.0), location: Optional(ToDo.Location(name: "Bar", coordinate: Optional(__C.CLLocationCoordinate2D(latitude: 37.331685100000001, longitude: -122.03006739999999))))))") -
As it can be clearly seen, the problem is that the timestamp is not the same in both, and I have no idea why it is changing.
EDIT: As #ganzogo found, there is a difference of exactly 18 hours between this too items. I am living in Ecuador which is GTM-5. Perhaps this could be a cue to figure out the problem.
After your line:
let dateFormatter = DateFormatter()
Try this:
dateFormatter.timeZone = TimeZone(secondsFromGMT: 64800)
If that doesn't work, try:
dateFormatter.timeZone = TimeZone(secondsFromGMT: -64800)
:-)
But you're kind of defeating the purpose of a unit test if you're just hacking it until in passes. You really need to understand whether the testItem or the item is exhibiting the correct behaviour right now, and that will depend on your application.
In func
test_Save_UsesGeocoderToGetCoordinateFromAddress()
timestamp transform to sut.dateTextField.text,then
In sut.save()
sut.dateTextField.text
transform to timestamp, the minute and second are drop

Issue Saving/Displaying CKAssets

I'm pretty new to swift, so please try to bear with me.
I'm currently able to download CKRecords and insert them into an array, "birdFacts". Each record includes a few strings, an image (CKAsset), a date, and an int. When they initially download from iCloud, everything works fine.
Everything is saving as expected, except the image. When I reload the data, the asset doesn't show up.
Here is my code to load saved data:
if let savedFacts = loadFacts() {
birdFacts = savedFacts
print("successfully loaded saved bird facts")
}
func loadFacts() -> [CKRecord]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(BirdFact.ArchiveURL.path!) as? [CKRecord]
}
This is my code to save the array:
func saveFacts() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(birdFacts, toFile: BirdFact.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save bird facts")
}
}
This is within my custom class definition file:
import UIKit
import CloudKit
class BirdFact: NSObject, NSCoding {
//MARK: PROPERTIES
var birdName: String
var photo: CKAsset
var birdFact: String
var date: NSDate
var sortingDate: Int
//MARK: TYPES
struct PropertyKey {
static let namekey = "name"
static let photokey = "photo"
static let factkey = "fact"
static let datekey = "date"
static let sortingDatekey = "sortingDate"
}
//MARK: INITIALIZATION
init?(birdName: String, photo: CKAsset, birdFact: String, date: NSDate, sortingDate: Int){
//init stored props
self.birdName = birdName
self.photo = photo
self.birdFact = birdFact
self.date = date
self.sortingDate = sortingDate
super.init()
if birdName.isEmpty || birdFact.isEmpty {
return nil
}
}
//MARK: NSCODING
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(birdName, forKey: PropertyKey.namekey)
aCoder.encodeObject(photo, forKey: PropertyKey.photokey)
aCoder.encodeObject(birdFact, forKey: PropertyKey.factkey)
aCoder.encodeObject(date, forKey: PropertyKey.datekey)
aCoder.encodeObject(sortingDate, forKey: PropertyKey.sortingDatekey)
}
required convenience init?(coder aDecoder: NSCoder) {
let birdName = aDecoder.decodeObjectForKey(PropertyKey.namekey) as! String
let photo = aDecoder.decodeObjectForKey(PropertyKey.photokey) as! CKAsset
let birdFact = aDecoder.decodeObjectForKey(PropertyKey.factkey) as! String
let date = aDecoder.decodeObjectForKey(PropertyKey.datekey) as! NSDate
let sortingDate = aDecoder.decodeObjectForKey(PropertyKey.sortingDatekey) as! Int
self.init(birdName: birdName, photo: photo, birdFact: birdFact, date: date, sortingDate: sortingDate)
}
//MARK: ARCHIVING PATHS
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("BirdFacts")
}
I'm saving whenever I finish downloading and sorting the records. Any idea what is going wrong?
EDIT: Included CloudKit query. I should note that I never save anything to iCloud, only download existing records.
func allprevFacts(date: String, olddate: Int){
act.startAnimating()
let container = CKContainer.defaultContainer()
let publicDB = container.publicCloudDatabase
//let factPredicate = NSPredicate(format: "recordID = %#", CKRecordID(recordName: date))
let factPredicate = NSPredicate(format: "date <= %#", NSDate())
let query = CKQuery(recordType: "BirdFacts", predicate: factPredicate)
publicDB.performQuery(query, inZoneWithID: nil) { (results, error) -> Void in
if error != nil {
print(error)
}
else {
dispatch_async(dispatch_get_main_queue()){
//print(results)
var count = 0
var sortedresults = [Int]()
for result in results! {
var b = result.valueForKey("sortingDate") as! Int
sortedresults.append(b)
}
print(sortedresults)
while count < sortedresults.count {
if sortedresults[count] <= olddate {
sortedresults.removeAtIndex(count)
}
else {
count = count + 1
}
}
print(sortedresults)
while sortedresults.count > 0 {
var d: Int = 0
let a = sortedresults.maxElement()
print(a)
while d < sortedresults.count{
if sortedresults[d] == a {
sortedresults.removeAtIndex(d)
self.birdFacts.append(results![d])
self.tableFacts.reloadData()
self.tableFacts.hidden = false
}
d = d + 1
print(d)
}
}
self.saveFacts()
print("saving bird facts")
self.tableFacts.hidden = false
}
}
}
act.stopAnimating()

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