How to query realm swift for a specific object - ios

Edited to simplify my question...
I'm new to Realm and so far, it's pretty cool, but I'm having an extremely hard time figuring out how to querying my Realm DB to check if a specific item exists in it.
Here's my Realm Model:
import Foundation
import RealmSwift
class ChartCount: Object{
dynamic var date: Date = Date()
dynamic var count: Int = Int(0)
}
In my main ViewController I'm storing a series of ChartCount objects for the 7 days of the current week using the following function:
// function to check if this weeks days have been created in Realm DB yet and creates them if not
let realm = try! Realm()
lazy var visitors: Results<VisitorCount> = { self.realm.objects(VisitorCount.self)}()
let startOfWeekDate = Date().startOfWeek(weekday: 1)
let nextDay = 24 * 60 * 60
var startOfWeek = try! Realm().objects(VisitorCount.self)
func setThisWeeksDays(){
if charts.count == 0 {
try! realm.write() {
let defaultVisitorDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)]
for visitors in defaultChartrDates {
let newChartDate = ChartCount()
newChartDate.date = visitors
self.realm.add(newChartrDate)
}
}
visitors = realm.objects(ChartCount.self)
}
}
And this to create the StartOfWeekDate
// Finds the start/end of the current week ----------------------------------------------- //
extension Date {
func startOfWeek(weekday: Int?) -> Date {
var cal = Calendar.current
var component = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
component.to12am()
cal.firstWeekday = weekday ?? 1
return cal.date(from: component)!
}
func endOfWeek(weekday: Int) -> Date {
let cal = Calendar.current
var component = DateComponents()
component.weekOfYear = 1
component.day = -1
component.to12pm()
return cal.date(byAdding: component, to: startOfWeek(weekday: weekday))!
}
func monthDay() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd"
return dateFormatter.string(from: self)
}
}
internal extension DateComponents {
mutating func to12am() {
self.hour = 0 + 24
self.minute = 0
self.second = 0
}
mutating func to12pm(){
self.hour = 0
self.minute = 0
self.second = 0
}
}// </end> Finds the start/end of the current week ------------------------------------------ //
All I want to do is check the 'date' column of my ChartDate model to see if there is an object in it that contains the first day of this week (e.g. startOfWeekDate).

For anyone looking to access Realm objects by Primary Key (Like I was) here's the code:
let specificPerson = realm.object(ofType: Person.self, forPrimaryKey: myPrimaryKey)

You cannot access Realm in the initializer, but you already have the answer in your code. Make start of week lazy just like you have for visitors and it will not be initialized until its used, and by the time your init is done. This is the way most of the realm examples are done.
lazy var startOfWeek: Result<ChartCount> = {
return realm.objects(ChartCount.self).filter("date = 'startOfWeekDate'")
}()
Alternatively you can make start of week an implicitly unwrapped optional and initialize it in viewDidLoad or just make it a regular optional
var startOfWeek: Result<ChartCount>!
...
//ViewDidLoad
realm.objects(ChartCount.self).filter("date = 'startOfWeekDate'")

OK, I think I've got it working. This is what I did:
To check if the Realm DB has the startOfWeekDate record I created this function:
func searchForStartOfWeek(findDate: Date) -> ChartCount?{
let predicate = NSPredicate(format: "date = %#", findDate as CVarArg)
let dateObject = self.realm.objects(ChartCount.self).filter(predicate).first
if dateObject?.date == findDate{
return dateObject
}
return nil
}
Then I used it to check if it exists:
func setThisWeeksDays(){
if searchForStartOfWeek(findDate: startOfWeekDate) == nil {
try! realm.write() {
let defaultChartDates = [startOfWeekDate, startOfWeekDate + TimeInterval(nextDay), startOfWeekDate + TimeInterval(nextDay*2), startOfWeekDate + TimeInterval(nextDay*3), startOfWeekDate + TimeInterval(nextDay*4), startOfWeekDate + TimeInterval(nextDay*5), startOfWeekDate + TimeInterval(nextDay*6)] // 3
for charts in defaultChartDates {
let newChartDate = ChartCount()
newChartDate.date = charts
self.realm.add(defaultChartDates)
}
}
visitors = realm.objects(ChartCount.self)
}
}
Thanks for everyones help!

Related

Unwrapping an Optional value in swift and realm

I wrote a working function for the application, but the error came out "The nil value was unexpectedly found when an optional value was implicitly deployed" limit Limit label.the text I can't fix.
Properties:
#IBOutlet weak var limitLabel: UILabel!
Function:
func leftLabels(){
let limit = self.realm.objects(Limit.self)
guard limit.isEmpty == false else {return}
limitLabel.text = limit[0].limitSum //Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
let calendar = Calendar.current
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let firstDay = limit[0].limitDate as Date
let lastDay = limit[0].limitLastDate as Date
let firstComponent = calendar.dateComponents([.year, .month, .day], from: firstDay)
let lastComponent = calendar.dateComponents([.year, .month, .day], from: lastDay)
let startDate = formatter.date(from: "\(firstComponent.year!)/\(firstComponent.month!)/\(firstComponent.day!) 00:00")
let endDate = formatter.date(from: "\(lastComponent.year!)/\(lastComponent.month!)/\(lastComponent.day!) 23:59")
let filterLimit: Int = realm.objects(SpendingDB.self).filter("self.date >= %# && self.date <= %#", startDate ?? "", endDate ?? "").sum(ofProperty: "cost")
ForThePeriod.text = "\(filterLimit)"
let a = Int(limitLabel.text!)!
let b = Int(ForThePeriod.text!)!
let c = a - b
availableForSpending.text = "\(c)"
I will be glad if you tell me the correct code
As from comments if appears that your view is not yet loaded and some of your views are still nil. Your app crashes because in line limitLabel.text = limit[0].limitSum the limitLabel is nil. It would crash regardless of Realm even by calling limitLabel.text = "Hello world!"
You can always guard data that you need to avoid changes in your code. Simply add
guard let limitLabel = limitLabel else { return nil }
guard let ForThePeriod = ForThePeriod else { return nil }
and so on.
I tried to clean up your code a bit. It is hard to understand what exactly are you trying to achieve but something like the following may seem a bit more appropriate:
func leftLabels() {
// Elements needed for method to execute.
guard let limitLabel = limitLabel else { return }
guard let forThePeriodLabel = forThePeriodLabel else { return }
guard let availableForSpendingLabel = availableForSpendingLabel else { return }
// Items that will be reused throughout the method later on
let limits: [Limit]
let firstLimit: Limit
let dates: (start: Date?, end: Date?)
let filterLimit: Int
limits = self.realm.objects(Limit.self)
guard limits.isEmpty == false else { return }
firstLimit = limits[0]
// limitLabel
limitLabel.text = firstLimit.limitSum
// Date components
dates = {
let calendar = Calendar.current
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let firstDay = firstLimit.limitDate as Date
let lastDay = firstLimit.limitLastDate as Date
let firstComponent = calendar.dateComponents([.year, .month, .day], from: firstDay)
let lastComponent = calendar.dateComponents([.year, .month, .day], from: lastDay)
let startDate = formatter.date(from: "\(firstComponent.year!)/\(firstComponent.month!)/\(firstComponent.day!) 00:00")
let endDate = formatter.date(from: "\(lastComponent.year!)/\(lastComponent.month!)/\(lastComponent.day!) 23:59")
return (startDate, endDate)
}()
// forThePeriodLabel
filterLimit = realm.objects(SpendingDB.self).filter("self.date >= %# && self.date <= %#", startDate ?? "", endDate ?? "").sum(ofProperty: "cost")
forThePeriodLabel.text = String(filterLimit)
// availableForSpendingLabel
availableForSpendingLabel.text = {
guard let a = Int(firstLimit.limitSum) else { return "" }
let b = filterLimit
let c = a - b
return String(c)
}()
}
Note some practices which help you better to structure and solve your code.
Guard dangerous data at first
Create a list of reusable items for your method (there should be as fewer as possible, in most cases none). Note how these can be later assigned to. And if you try using it before assigning to it, you will be warned by your compiler.
Wrap as much code into closed sections such as availableForSpendingLabel.text = { ... code here ... }()
Use tuples such as let dates: (start: Date?, end: Date?)
Don't be afraid of using long names such as availableForSpendingLabel
I would even further try and break this down into multiple methods. But I am not sure what this method does and assume that you have posted only part of it...
========== EDIT: Adding alternate approach ==========
From comments this is a financial application so probably at least dealing with Decimal numbers would make sense. Also introducing approach with adding a new structure which resolves data internally. A formatter is also used to format the number. And some other improvements:
struct Limit {
let amount: Decimal
let startDate: Date
let endDate: Date
}
struct Spending {
let cost: Decimal
let date: Date
}
struct LimitReport {
let limitAmount: Decimal
let spendingSum: Decimal
let balance: Decimal
init(limit: Limit) {
let limitAmount: Decimal = limit.amount
let spendingSum: Decimal = {
let calendar = Calendar.autoupdatingCurrent // Is this OK or should it be some UTC or something?
func beginningOfDate(_ date: Date) -> Date {
let components = calendar.dateComponents([.day, .month, .year], from: date)
return calendar.date(from: components)!
}
let startDate = beginningOfDate(limit.startDate)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)
let spendings: [Spending] = realm.objects(Spending.self).filter { $0.date >= startDate && $0.date < endDate }
return spendings.reduce(0, { $0 + $1.cost })
}()
let balance = limitAmount - spendingSum
self.limitAmount = limitAmount
self.spendingSum = spendingSum
self.balance = balance
}
}
func leftLabels() {
// Elements needed for method to execute.
guard let limitLabel = limitLabel else { return }
guard let forThePeriodLabel = forThePeriodLabel else { return }
guard let availableForSpendingLabel = availableForSpendingLabel else { return }
guard let limit = self.realm.objects(Limit.self).first else { return }
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = "$"
let report = LimitReport(limit: limit)
limitLabel.text = formatter.string(from: report.limitAmount)
forThePeriodLabel.text = formatter.string(from: report.spendingSum)
availableForSpendingLabel.text = formatter.string(from: report.balance)
}
Matic provided a good, comprehensive answer to your question (voted). I thought I'd provide an answer narrowly focused on your crash and a "short and sweet" way to fix it:
The line in question could crash 2 different ways:
limitLabel.text = limit[0].limitSum //Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Your limitLabel IBOutlet is declared as an "implicitly unwrapped Optional" (Note the ! after the type, UILabel:
#IBOutlet weak var limitLabel: UILabel!
An implicitly unwrapped Optional is an Optional where, essentially, the compiler adds a hidden "!" force-unwrap every time you try to reference that object.
That means that
limitLabel.text = //something
Is compiled as
limitLabel!.text = //something
and if limitLabel is nil, you crash.
If you call your leftLabels() function before your view has been loaded, or if that outlet is never connected, you will crash.
You can fix that by adding an optional unwrap to the statement:
limitLabel?.text = //something
(That construct is known as "optional chaining".)
Given that the crash message you're getting mentions "implicitly unwrapping an Optional value" it's likely that that is what is crashing in your case. However, you should fix the other issue as well.
The second way you can crash is in your array indexing.
limitLabel.text = limit[0].limitSum
When you fetch an object from an array by index, your app will crash if the array does not contain an item at that index. The expression limit[0] will crash if the limit array is empty.
The array type has a computed property first that will return an optional if the array is empty.
You should change that to limit.first?.limitSum.
Change the whole line to be:
limitLabel?.text = limit.first()?.limitSum
And it won't crash any more.

Convert String minutes seconds to Int

I've a string with minutes and seconds in format "minutes:seconds". For example, "5:36". I want to convert it to Int value. For example "5:36" string should be 336 Int value. How this can be done?
let timeString = "5:36"
let timeStringArray = timeString.split(separator: ":")
let minutesInt = Int(timeStringArray[0]) ?? 0
let secondsInt = Int(timeStringArray[1]) ?? 0
let resultInt = minutesInt * 60 + secondsInt
print(resultInt)
Here's a simple extension you can use which will validate the format of your input string too:
import Foundation
extension String {
func toSeconds() -> Int? {
let elements = components(separatedBy: ":")
guard elements.count == 2 else {
print("Provided string doesn't have two sides separated by a ':'")
return nil
}
guard let minutes = Int(elements[0]),
let seconds = Int(elements[1]) else {
print("Either the minute value or the seconds value cannot be converted to an Int")
return nil
}
return (minutes*60) + seconds
}
}
Usage:
let testString1 = "5:36"
let testString2 = "35:36"
print(testString1.toSeconds()) // prints: "Optional(336)"
print(testString2.toSeconds()) // prints: "Optional(2136)"
I tried out your example on the playground here's the code:
import Foundation
let time1String = "0:00"
let time2String = "5:36"
let timeformatter = DateFormatter()
timeformatter.dateFormat = "m:ss"
let time1 = timeformatter.date(from: time1String)
let time2 = timeformatter.date(from: time2String)
if let time1 = time1 {
print(time2?.timeIntervalSince(time1)) // prints: Optional(336.0)
}

Swift Firebase Multithreading Issue

I'm trying to run a couple of for loops inside of a function that should return an array of strings.
Where I'm having trouble is with getting the correct results BEFORE the next for loop is run...and then again returning that results BEFORE I need to return the array of strings to complete the function.
In the first case, I have a for loop that's getting data from Firebase. I was able to use a dispatch group to get the value to print out - but then with the other loop after this - I was having issues from using the dispatch group in the prior task.
The code all works perfectly if executed with the correct values but I'm not sure how to go about this with regards to threading. Would really appreciate any help.
func findTopSpots() -> [String] {
var topFive = [String]()
var locationRatingDictionary = [String:Double]()
let myGroup = DispatchGroup()
let locationsArray = ["wyoming", "kansas", "arkansas", "florida", "california"]
// Use the days to find the most common month
let calendar = NSCalendar.current
var monthArray = [String]()
var date = self.departureDate!
let endDate = self.returnDate!
// Formatter for printing the month name
let fmt = DateFormatter()
fmt.dateFormat = "MMMM"
// Add each days month to an array
while date <= endDate {
date = calendar.date(byAdding: .day, value: 1, to: date)!
monthArray.append(fmt.string(from: date))
}
// Return the primary month from function
let primaryMonth = findMostCommonMonthInArray(array: monthArray).lowercased()
// Create a dictionary of location:rating for the primary month
for doc in locationsArray {
self.db.collection("locations").document(doc).collection("historic").document(primaryMonth).getDocument { (document, err) in
if let document = document, document.exists {
let rating = document["rating"] as? Double
locationRatingDictionary[doc] = rating
} else {
print("Document does not exist")
}
}
}
//---- THE CODE BELOW WILL NOT PRINT WITH ANY VALUES ----//
print(locationRatingDictionary)
// Sort the tuple array by rating
let locationRatingTupleArray = locationRatingDictionary.sorted{ $0.value > $1.value }
// Return 5 results
for (location,rating) in locationRatingTupleArray.prefix(5) {
print(location,rating)
topFive.append(location)
}
print("top five are \(topFive)")
return topFive
}
The issue here is that the firebase returns with query results asynchronously and you are not waiting for it to return.
I can see that you have instantiate DispatchGroup but have not used it. Lets try to use it to solve your issue. Also, you would need to change the method signature to take a closure. This avoids blocking thread to return function output.
func findTopSpots(completionHandler:([String])->Void) {
var topFive = [String]()
var locationRatingDictionary = [String:Double]()
let myGroup = DispatchGroup()
let locationsArray = ["wyoming", "kansas", "arkansas", "florida", "california"]
// Use the days to find the most common month
let calendar = NSCalendar.current
var monthArray = [String]()
var date = self.departureDate!
let endDate = self.returnDate!
// Formatter for printing the month name
let fmt = DateFormatter()
fmt.dateFormat = "MMMM"
// Add each days month to an array
while date <= endDate {
date = calendar.date(byAdding: .day, value: 1, to: date)!
monthArray.append(fmt.string(from: date))
}
// Return the primary month from function
let primaryMonth = findMostCommonMonthInArray(array: monthArray).lowercased()
// Create a dictionary of location:rating for the primary month
for doc in locationsArray {
myGroup.enter() self.db.collection("locations").document(doc).collection("historic").document(primaryMonth).getDocument { (document, err) in
if let document = document, document.exists {
let rating = document["rating"] as? Double
locationRatingDictionary[doc] = rating
} else {
print("Document does not exist")
}
myGroup.leave()
}
}
myGroup.notify(queue:.main) {
//---- THE CODE BELOW WILL NOT PRINT WITH ANY VALUES ----//
print(locationRatingDictionary)
// Sort the tuple array by rating
let locationRatingTupleArray = locationRatingDictionary.sorted{ $0.value > $1.value }
// Return 5 results
for (location,rating) in locationRatingTupleArray.prefix(5) {
print(location,rating)
topFive.append(location)
}
print("top five are \(topFive)")
completionHandler(topFive)
}
}
Your code is asynchronous fastest way is dispatchGroup with completion
//
func findTopSpots(completion:#escaping(_ arr:[string])->void){
let dispatchGroup = DispatchGroup()
var topFive = [String]()
var locationRatingDictionary = [String:Double]()
let locationsArray = ["wyoming", "kansas", "arkansas", "florida", "california"]
// Use the days to find the most common month
let calendar = NSCalendar.current
var monthArray = [String]()
var date = self.departureDate!
let endDate = self.returnDate!
// Formatter for printing the month name
let fmt = DateFormatter()
fmt.dateFormat = "MMMM"
// Add each days month to an array
while date <= endDate {
date = calendar.date(byAdding: .day, value: 1, to: date)!
monthArray.append(fmt.string(from: date))
}
// Return the primary month from function
let primaryMonth = findMostCommonMonthInArray(array: monthArray).lowercased()
// Create a dictionary of location:rating for the primary month
for doc in locationsArray {
dispatchGroup.enter()
self.db.collection("locations").document(doc).collection("historic").document(primaryMonth).getDocument { (document, err) in
if let document = document, document.exists {
let rating = document["rating"] as? Double
locationRatingDictionary[doc] = rating
} else {
print("Document does not exist")
}
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
//---- THE CODE BELOW WILL NOT PRINT WITH ANY VALUES ----//
print(locationRatingDictionary)
// Sort the tuple array by rating
let locationRatingTupleArray = locationRatingDictionary.sorted{ $0.value > $1.value }
// Return 5 results
for (location,rating) in locationRatingTupleArray.prefix(5) {
print(location,rating)
topFive.append(location)
}
print("top five are \(topFive)")
completion(topFive)
}
}

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!

How to check NSDate yyyy/mm/dd in NSArray and compare it?

I have an NSArray, inside I have a var of kind NSDate
which give this format "timeStamp = "2015-08-18 16:58:31"
I want to compare in all the array the date only 2015-08-18
compare it and if same date only the first one show full NSDate
and the rest with same date show only the time on UI
This is what I did so far:
func getAllMessages() -> NSArray{
var allMessages = self.mutableSetValueForKey("messages").allObjects as NSArray
let timeStampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: true)
var sortByTime = allMessages.sortedArrayUsingDescriptors([timeStampSortDescriptor])
println("\(sortByTime)")
return sortByTime
}
screen shot
http://i.stack.imgur.com/wcsSz.jpg
After some research i did made a solution as following
First this extension is very good and my way is depends on it
https://stackoverflow.com/a/27369380/5188737
If anyone have better solution or clean
I will appreciate if you can post it here
I'm sorry there's no comments
func loadMessages(){
if chatRoom!.messages.count > 0{
var i = 0
var tempMsgDate:NSDate?
var chatMessage:ChatMessage?
for message in chatRoom!.getAllMessages(){
let msg = message as! Message
if i == 0{
tempMsgDate = msg.timeStamp
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: convertNSDateToString(msg.timeStamp))
i++
}else{
//if the tempMsgDate (which is the first of the same
//date in the nsarray)
if checkIfSameDayDate(tempMsgDate!,date2: msg.timeStamp){
var tempDate = msg.timeStamp.time
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.dateFromString(tempDate)
println("loadmessages method: \(date?.time)")
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: msg.timeStamp.time)
}else{//after he got to different date it save it as
//first of same date to follow
tempMsgDate = msg.timeStamp
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: convertNSDateToString(msg.timeStamp))
}
}
var msgCollection:[ChatMessage] = [ChatMessage]()
msgCollection.append(chatMessage!)
chat.loadedMessages.append(msgCollection)
}
}
}
func convertNSDateToString(date:NSDate) -> String{
let dateString = date.date + " " + date.time
println("in convert: \(dateString)")
return dateString
}
func checkIfSameDateFromSendMSGAndReciveMSG(date:NSDate) -> Bool{
for message in chatRoom!.getAllMessages(){
let msg = message as! Message
if msg.timeStamp.date == date.date{
return true
}
}
return false
}
//checks if the date1 equal to date2
func checkIfSameDayDate(date1:NSDate,date2:NSDate) -> Bool{
if date1.date == date2.date{
return true
}
return false
}

Resources