Swift: Schedule a local notification for a specific time on weekdays - ios

Hi I am trying to schedule a local notification to fire at 9:00am on weekdays (mon - fri) and cant seem to find any documentation on how to do this. Here is my code so far:
#IBAction func scheduleLocal(sender: UIButton) {
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return
}
if settings.types == .None {
let ac = UIAlertController(title: "Cant Schedule", message: "No Permission", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
return
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.alertBody = "Come Exercise"
notification.alertAction = "Exercise Time"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["customField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
and in viewDidLoad:
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)

This is my class example you can use it as you want , i also support Arabic language by translate Arabic number to English .
//
// notification.swift
// NSFetchController Pro
//
// Created by Mr.Geeker on 08/02/15.
// Copyright (c) 2015 X2coder. All rights reserved.
//
import UIKit
class notification {
func createNotification(#hour:String, day:String, msgBody:String)->Bool
{
if(self.checkifNotificationOnOrOff())
{
//println("\(araToString(hour))")
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var convertedTime:String = ""
var testDate:NSDate = NSDate()
var timeFormat:NSString = dateFormatter.stringFromDate(testDate)
// Get the range of date (AM OR PM )
var amRange:NSRange = timeFormat.rangeOfString(dateFormatter.AMSymbol)
var pmRange:NSRange = timeFormat.rangeOfString(dateFormatter.PMSymbol)
var is24h:Bool = (amRange.location == NSNotFound && pmRange.location == NSNotFound)
if is24h {
araToString(hour)
}else{
var dateFormatter2:NSDateFormatter = NSDateFormatter()
dateFormatter2.dateFormat = "HH:mm"
var hourDate:NSDate = dateFormatter2.dateFromString(hour)!
var pmAmDateString:NSString = dateFormatter2.stringFromDate(hourDate)
convertedTime = pmAmDateString
println(convertedTime)
}
var hourAndMiOnly:NSArray = convertedTime.componentsSeparatedByString(":")
var onlyHour:Int = 0
var onlyMinuts:Int = 0
for var i:Int = 0; i < 2; i++ {
for thimes in hourAndMiOnly
{
if i == 0
{
onlyMinuts = thimes.integerValue
}
if i == 1 {
// we should add -1 before the class
onlyHour = (thimes.integerValue)
if onlyHour < 1
{
onlyHour = 00
}
break
}
}
}
let DaysDic = [0:"None",1:"Sunday",2 :"Monday",3 :"Tuesday",4 :"Wednesday",5 :"Thursday",6 :"Friday",7 :"Saturday"]
var ConvertDayToInt:Int?{
for (key,value) in DaysDic
{
if value == day
{
return key
}
}
return nil
}
//println("Hour is \(onlyHour) And Minut \(onlyMinuts) AND Day \(ConvertDayToInt)")
let date = NSDate()
var userInfo: [NSObject : AnyObject]?
var createCalender:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var dateComponenet:NSDateComponents = createCalender.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.WeekCalendarUnit, fromDate: date)
dateComponenet.weekday = ConvertDayToInt!
dateComponenet.hour = onlyHour
dateComponenet.minute = onlyMinuts
var fireDateToRun:NSDate = createCalender.dateFromComponents(dateComponenet)!
var notificationClass:UILocalNotification = UILocalNotification()
notificationClass.alertBody = msgBody
notificationClass.fireDate = fireDateToRun
notificationClass.soundName = UILocalNotificationDefaultSoundName
notificationClass.repeatInterval = NSCalendarUnit.WeekCalendarUnit
notificationClass.timeZone = NSTimeZone.defaultTimeZone()
notificationClass.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduledLocalNotifications = [notificationClass]
}else{
// call protocol function not support notification
}
return true
}
func araToString(numericString:String)->NSString
{
var nsMutString:NSMutableString = NSMutableString(string: numericString)
let ArabicString:NSString = "١٢٣٤٥٦٧٨٩:"
let EnglishString:NSString = "123456789:"
for ( var i:Int = 0 ; i < ArabicString.length ; i++)
{
var a:NSString = ArabicString.substringWithRange(NSMakeRange(i, 1))
var w:NSString = EnglishString.substringWithRange(NSMakeRange(i, 1))
nsMutString.replaceOccurrencesOfString(a, withString: w, options: NSStringCompareOptions.LiteralSearch, range:NSMakeRange(0, nsMutString.length))
}
return nsMutString
}
func deleteAll(){
let appnoti = UIApplication.sharedApplication()
let delArray = appnoti.scheduledLocalNotifications
if delArray.count > 0
{
appnoti.cancelAllLocalNotifications()
}
}
func checkifNotificationOnOrOff()->Bool
{
let systemVer:String = UIDevice.currentDevice().systemVersion
var finalFloat:Float = NSString(string: systemVer).floatValue
if finalFloat < 8 {
return false
}else{
return true
}
}
}

Related

Changes in the datepicker widgets in iOS?

In our iOS app we have a timepicker widget to book appointments. This has worked fine for a long time. We just changed iOS developer and when he rebuilt the app the timepicker is broken for some reason we cannot tell. Has something changed recently in XCode/iOS that could explain why the layout suddenly is broken?
How it was
How it is now
This is the code responsible:
This timepicker is based on the standard iOS UIDatePicker.
class TimePickerController: UIViewController {
#IBOutlet weak var notAvailableLbl: UILabel!
#IBOutlet weak var fromPicker: UIDatePicker!
#IBOutlet weak var toPicker: UIDatePicker!
#IBOutlet weak var switchNotAvailable: UISwitch!
var object: EventElement?
var delegate:TimePickerControllerDelegate?
var name: DEFAULT_AVAILABILITY_CONST!
var startTime,endTime: Date?
var isFromSettings:Bool = false
var isNotAvailable: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = AppColors.Primary
switchNotAvailable.setOn(isNotAvailable, animated: true)
switchChanged(switchNotAvailable)
setPickerLocale(withIdentifier: "en_GB")
setPickerTimezone(withIdentifier: "UTC")
initPickerDates()
if object?.type == EVENT_CONST.lunch{
switchNotAvailable.isHidden = true
notAvailableLbl.isHidden = true
}else{
switchNotAvailable.isHidden = false
notAvailableLbl.isHidden = false
}
}
func setPickerLocale(withIdentifier locale: String) {
// Changing to 24 hrs
let local = NSLocale(localeIdentifier: locale) as Locale
fromPicker.locale = local
toPicker.locale = local
}
func setPickerTimezone(withIdentifier timeZone: String) {
//set timezone
fromPicker.timeZone = TimeZone.init(identifier: timeZone)
toPicker.timeZone = TimeZone.init(identifier: timeZone)
}
func initPickerDates() {
if let obj = object {
let startTime = obj.start.split(separator: "Z")
let endTime = obj.end.split(separator: "Z")
if(startTime.first == endTime.first)
{
fromPicker.date = getTimeFromString(stringTime: String("08:00"))
toPicker.date = getTimeFromString(stringTime: String("22:00"))
}
else{
fromPicker.date = getTimeFromString(stringTime: String(startTime.first ?? "08:00"))
toPicker.date = getTimeFromString(stringTime: String(endTime.first ?? "22:00"))
}
}else {
if let start = startTime,let end = endTime {
if(start == end)
{
// 8.00 to 22.00
fromPicker.date = start
toPicker.date = end.dateByAddingHours(hours: 14)
}
else{
fromPicker.date = start
toPicker.date = end
}
}
}
}
func getTimeFromString(stringTime: String) -> Date
{
let local = NSLocale(localeIdentifier: "en_GB") as Locale
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.locale = local
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
let date = dateFormatter.date(from: stringTime) ?? Date()
print(date)
return date
}
#IBAction func btnDone(_ sender: Any) {
print(fromPicker.date)
print(toPicker.date)
updateEvent()
}
func updateEvent() {
var start = fromPicker.date.timeDisplay + "Z"
var end = toPicker.date.timeDisplay + "Z"
var createdDate:String = ""
var id:String = ""
var name:String = ""
if object == nil {
start = fromPicker.date.ISOISO8601StringForAvailability + "Z"
end = toPicker.date.ISOISO8601StringForAvailability + "Z"
createdDate = Date().toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm:ss")) + "Z"
id = UUID().uuidString.lowercased()
name = self.name.rawValue
}
else{
createdDate = object?.created ?? ""
id = object?.id ?? ""
name = (object?.name.rawValue) ?? ""
}
print("switch state",switchNotAvailable.isOn)
if switchNotAvailable.isOn {
if let startT = startTime,let endT = endTime {
let startDt = "08:00Z".formatDateWithTime(referenceDate: startT)
let endDt = "08:00Z".formatDateWithTime(referenceDate: endT)
start = startDt!.toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm"),timezone: "UTC") + "Z"
end = endDt!.toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm"),timezone: "UTC") + "Z"
}
else{
start = "08:00Z"
end = "08:00Z"
}
}
ActivityIndicator().showIndicator(backgroundColor: nil)
print("start and end date : ",start," ",end)
let type:String?
if isFromSettings == true{
type = object?.type.rawValue
}
else{
type = "AVAILABILITY_PATCH"
}
print(type ?? "AVAILABILITY_PATCH")
APICalls().updateAvailability(start: start, end: end, name: name, type: type ?? "AVAILABILITY_PATCH", created: createdDate,id: id ) { (response) in
ActivityIndicator().hideIndicator()
if let result = response
{
let res = Event.init(dictionary: result as? NSDictionary ?? [:])
DatabaseManager.getInstance().saveAvailability(object: res)
self.delegate?.didSelectTime(from: self.fromPicker.date, to: self.toPicker.date)
self.navigationController?.popViewController(animated: true)
}
}
}
To disable this time picker style, you have to add below line.
fromPicker.preferredDatePickerStyle = .wheels
In IOS 14 we have to define DatePickerStyle.
Please write these two lines in initPickerDates() method to set picker wheel style
fromPicker.preferredDatePickerStyle = .wheels
toPicker.preferredDatePickerStyle = .wheels
In IOS 14, we have multiple styles for date pickers. So this is the default behavior in iOS 14.
You just need to add the following line in the initPickerDates() method.
fromPicker.preferredDatePickerStyle = .wheels
toPicker.preferredDatePickerStyle = .wheels

How to integrate PayUMoney in swift

I want to integrate the PayUMoney SDK in my app using
I am using this link to integrate PayUMoney: How to integrate PayU Money in swift
I can see only the option to pay by credit card referring to the link's sample code however it is not showing up the net banking option. I don't understand what I am doing wrong in my code.
Here's what I have tried -
import UIKit
import PlugNPlay
import CommonCrypto
class PaymentVC: UIViewController {
var type = String()
var email = String()
var name = String()
var phone = String()
var address = String()
var state = String()
var zipcode = String()
var officetype = Int()
var TotalAmmount = String()
override func viewDidLoad() {
super.viewDidLoad()
continueWithCardPayment()
// Do any additional setup after loading the view.
}
#IBAction func backButtonAction(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
func continueWithCardPayment()
{
var paymentParam = PUMTxnParam()
paymentParam.key = "Zegfsgh"
paymentParam.merchantid = "7085776"
paymentParam.txnID = "xyz"
paymentParam.phone = "8770338859"
paymentParam.amount = TotalAmmount
paymentParam.productInfo = "Nokia"
paymentParam.surl = "https://test.payumoney.com/mobileapp/payumoney/success.php"
paymentParam.furl = "https://test.payumoney.com/mobileapp/payumoney/failure.php"
paymentParam.firstname = "john"
paymentParam.email = "john#john.com"
paymentParam.environment = PUMEnvironment.test
paymentParam.udf1 = "udf1"
paymentParam.udf2 = "udf2"
paymentParam.udf3 = "udf3"
paymentParam.udf4 = "udf4"
paymentParam.udf5 = "udf5"
paymentParam.udf6 = ""
paymentParam.udf7 = ""
paymentParam.udf8 = ""
paymentParam.udf9 = ""
paymentParam.udf10 = ""
paymentParam.hashValue = self.getHashForPaymentParams(paymentParam)
// paymentParam. = ""
// Set this property if you want to give offer:
// paymentParam.userCredentials = ""
PlugNPlay.presentPaymentViewController(withTxnParams: paymentParam, on: self, withCompletionBlock: { paymentResponse, error, extraParam in
if error != nil {
UIUtility.toastMessage(onScreen: error?.localizedDescription, from: .none)
} else {
var message = ""
if paymentResponse?["result"] != nil && (paymentResponse?["result"] is [AnyHashable : Any]) {
print(paymentResponse!)
message = "Hello Asad sucess"
// message = paymentResponse?["result"]?["error_Message"] as? String ?? ""
// if message.isEqual(NSNull()) || message.count == 0 || (message == "No Error") {
// message = paymentResponse?["result"]?["status"] as? String ?? ""
// }
} else {
message = paymentResponse?["status"] as? String ?? ""
}
UIUtility.toastMessage(onScreen: message, from: .none)
}
})
PlugNPlay.presentPaymentViewController(withTxnParams: paymentParam, on: self, withCompletionBlock: .none)
}
func sha512(_ str: String) -> String {
let data = str.data(using:.utf8)!
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
data.withUnsafeBytes({
_ = CC_SHA512($0, CC_LONG(data.count), &digest)
})
return digest.map({ String(format: "%02hhx", $0) }).joined(separator: "")
}
func getHashForPaymentParams(_ txnParam: PUMTxnParam?) -> String? {
let salt = "vw8LigfjD"
var hashSequence: String? = nil
if let key = txnParam?.key, let txnID = txnParam?.txnID, let amount = txnParam?.amount, let productInfo = txnParam?.productInfo, let firstname = txnParam?.firstname, let email = txnParam?.email, let udf1 = txnParam?.udf1, let udf2 = txnParam?.udf2, let udf3 = txnParam?.udf3, let udf4 = txnParam?.udf4, let udf5 = txnParam?.udf5, let udf6 = txnParam?.udf6, let udf7 = txnParam?.udf7, let udf8 = txnParam?.udf8, let udf9 = txnParam?.udf9, let udf10 = txnParam?.udf10 {
hashSequence = "\(key)|\(txnID)|\(amount)|\(productInfo)|\(firstname)|\(email)|\(udf1)|\(udf2)|\(udf3)|\(udf4)|\(udf5)|\(udf6)|\(udf7)|\(udf8)|\(udf9)|\(udf10)|\(salt)"
}
let hash = self.sha512(hashSequence!).description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
return hash
}
func paymentResponseReceived(notify:NSNotification) {
print(notify)
}
}

How to display indian and euro locale number value in words?

I am struggling to show the Indian and Euro Locale value in words. Please anyone help on this.
var outputString = ""
let valueString = "9,58,888.875"
let valueFormatter = NSNumberFormatter()
let outputFormatter = NSNumberFormatter()
outputFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
valueFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
outputString = valueFormatter.stringFromNumber(outputFormatter.numberFromString(valueString as String)!)!
print(outputString)
I know it's very late. I have tried following solution, might not the best one but it's working for me. Hope it will be useful.
Note: - I have considered only till crore scale
#IBAction func startBtnClicked(sender: AnyObject) {
if var amountStr = ammountTextField.text
{
let numberFormater = NSNumberFormatter()
if amountStr.containsString(",")
{
amountStr = amountStr.stringByReplacingOccurrencesOfString(",", withString: "")
}
//eg: - amountStr = "45678432"
if let amountNumber = numberFormater.numberFromString(amountStr)
{
//First get currency format
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.currencySymbol = ""
currencyFormatter.locale = NSLocale(localeIdentifier: "en_IN")
let amountInCurrencyFormatStr = currencyFormatter.stringFromNumber(amountNumber)
//amountInCurrencyFormatStr = "4,56,78,432"
var outputStr = ""
//Get each component in array
if let amountInCurrencyFormatComponentArray = amountInCurrencyFormatStr?.componentsSeparatedByString(",")
{
//[4,56,78,432]
let scaleStrArr = ["thousand","lakh","crore"]
let spellFormatter = NSNumberFormatter()
spellFormatter.numberStyle = .SpellOutStyle
var scaleStrCount = 0
for var i = (amountInCurrencyFormatComponentArray.count - 1) ; i >= 0 ; i--
{
//Iterate array, and append scale strings (["thousand","lakh","crore"]) at proper place
if let currencyStr = spellFormatter.stringFromNumber(numberFormater.numberFromString(amountInCurrencyFormatComponentArray[i])!)
{
if i == (amountInCurrencyFormatComponentArray.count - 1)
{
outputStr = currencyStr
}
else
{
if scaleStrCount < scaleStrArr.count
{
outputStr = "\(currencyStr) \(scaleStrArr[scaleStrCount]) \(outputStr)"
scaleStrCount++
}
else
{
outputStr = "\(currencyStr) \(outputStr)"
}
}
}
else
{
print("ERROR: - Unable to spell")
}
}
}
else
{
print("ERROR: - No , in text field")
}
ammountTextField.text = amountInCurrencyFormatStr
print("OUTPUT --> \(outputStr)")
//OUTPUT -> "four crore fifty-six lakh seventy-eight thousand four hundred thirty-two"
}
else
{
print("ERROR: - No Number in text field")
}
}
else
{
print("ERROR: - No value in text field")
}
}

Stop notifications at specific time using UIDatePicker

I managed to setup notifications using a UIDatePicker but my problem is that I want to make them stop by using an other UIDatePicker (datePickerStop).
So basically it Schedules to start and end notifications with two different UIDatePickers inside a Switch object and an if statement.
This is code that I have but it doesn't seem to work or I don't place it in the right place.
Any ideas?
let notificationArray = UIApplication.sharedApplication().scheduledLocalNotifications!
for notification in notificationArray {
if notification.fireDate == fixedNotificationDate(datePickerStop.date) {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
}
This is the complete code
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("SwitchState") != nil) {
SwitchOutlet.on = defaults.boolForKey("SwitchState")
}
if (SwitchOutlet.on) {
Label1Outlet.text = "Notifications are On"
} else {
Label1Outlet.text = "Notifications are Off"
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Switch(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
if (SwitchOutlet.on) {
Label1Outlet.text = "Notifications are On"
defaults.setBool(true, forKey: "SwitchState")
let notification = UILocalNotification()
notification.fireDate = fixedNotificationDate(datePicker.date)
notification.repeatInterval = NSCalendarUnit.Minute
notification.alertBody = “Message”
notification.alertAction = “Lock!”
notification.soundName = "NotifSound.caf"
notification.userInfo = ["CustomField1": "w00t"]
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return }
if settings.types == .None {
let ac = UIAlertController(title: "Can't Activate", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
return
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
} else {
Label1Outlet.text = "Notifications are Off"
defaults.setBool(false, forKey: "SwitchState")
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
}
func fixedNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponents: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponents.second = 0
let fixedDate: NSDate = NSCalendar.currentCalendar().dateFromComponents(dateComponents)!
return fixedDate
}
func updateUI() {
let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
if currentSettings?.types != nil {
if currentSettings!.types == [UIUserNotificationType.Badge, UIUserNotificationType.Alert] {
}
else if currentSettings!.types == [UIUserNotificationType.Badge] {
}
else if currentSettings!.types == UIUserNotificationType.None {
}
}
}
}
You can add userInfo to your notification when scheduled
let notification:UILocalNotification = UILocalNotification()
notification.userInfo = ["day": day, "hour": hour]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
And when you are trying to cancel just find it with the userInfo
let app = UIApplication.sharedApplication()
let day: Int = 1
let hour: Int = 2
for singleNotification in app.scheduledLocalNotifications!{
let notDay = singleNotification.userInfo!["day"] as! Int
let notHour = singleNotification.userInfo!["hour"] as! Int
if(notDay == day && notHour == hour){
app.cancelLocalNotification(singleNotification)
break;
}
}
I used Int but it is a Dictionary

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