how to make call to 2 numbers depending om the time - ios

sorry for all the questions im new to iOS but im wondering is it possible to set a time frame in iOS for example if user push button call me between the time 6am - 6pm the dialer opens and makes the phone call to a nr 567895432 but if it is after hours for example between 6,01pm - 7,59am
if button call me pushed the user would call 89780324, I know this is possible on php if I should create a Webview app but this is a native app and I don't really want to access a data base just a simple 2way app that sends requests,
thank you in advance

If I understood it correctly,On button tap, you want to call two different numbers based on time.
Why don't you check on button press
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if ((currentHour > 6) && (currentHour < 18)) {
call 567895432
}
else{
call 89780324
}

In swift 3.0
var components: DateComponents? =
Calendar.current.dateComponents(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit, from: Date())
var currentHour: Int? = components?.hour
var currentMinute: Int? = components?.minute
var currentSecond: Int? = components?.second
if (currentHour > 6) && (currentHour < 18) {
call
567895432
}
else {
call
89780324
}

Related

Calculate duration between two dates(finding upcoming/old birthdays) in ios [duplicate]

This question already has answers here:
Number of days between two NSDates [duplicate]
(16 answers)
Closed 6 years ago.
How can i calculate duration between two dates. like
I am getting contacts birthday list from contacts framework. Now i want to compare Today date with user DOB value and i should display the "remaining days count"(birthday).
For Example:
In contacts i added one user like: DOB: dd/MM/yyyy -->12/04/1960
now today date is: 25/04/2016
I want to get the upcoming birthday date(duration between two dates)
o/p: 18 days
How can i get this
Try below line of code. you will get the solution.
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: startDate toDate: endDate options: 0];
days = [components day];
Use the following
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:fistDate toDate:secondDate options:0];
int months = [conversionInfo month]; // to get number of months
int days = [conversionInfo day]; // to get number of days
int hours = [conversionInfo hour]; // to get hour difference
int minutes = [conversionInfo minute]; // to get hour difference
copied from Difference between two NSDates

Get NSDate from start of 7 days ago

I'm trying to do some simple 7 day history plotting. Given the current NSDate.date, I want to get the NSDate that corresponds to the start of day, 7 days ago. So basically 7 days prior to 0.00 this morning.
What I've tried, is the following:
// decompose the current date, do I need more component fields?
NSDateComponents *comps = [NSCalendar.currentCalendar components: NSDayCalendarUnit fromDate: NSDate.date];
NSLog(#"components: %#", comps);
// Back day up 7 days. Will this wrap appropriate across month/year boundaries?
comps.day -= 7;
NSDate *origin = comps.date;
NSLog(#"new date: %#", origin);
What I assumed was that by just specifying NSDayCalendarUnit, the other things would be defaults (like start of day, etc). Unfortunately, origin ends up as (null). What is the correct way to do this?
To construct a new date you should know not only a day but also a month and a year. So you should add NSYearCalendarUnit | NSMonthCalendarUnit. Also you should setup calendar and probably timezone properties of NSDateComponents's instance:
NSDateComponents *comps = [NSCalendar.currentCalendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate: NSDate.date];
comps.calendar = NSCalendar.currentCalendar;
comps.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSLog(#"components: %#", comps);
// Back day up 7 days. Will this wrap appropriate across month/year boundaries?
comps.day -= 7;
NSDate *origin = comps.date;
NSLog(#"new date: %#", origin);

Iterating over a year to get each days NSDate object in Swift

Hello I have a method that returns an array of times for each day.
prayTimesDate(date: NSDate, latitide : Double, longitude : Double, timeZone : Double) -> NSMutableArray
I need to iterate through a whole year or maybe a date range to get an array of times for each day in a whole year. I found alot of references in ruby and python on how to do this but I couldn't find anything for swift or objective-c. Is there any built in methods in swift that will accomplish this? If not can someone help me out as I am still new in programming. Any input is greatly appreciated.
This is the objective-c code for the method I'm linking to my swift project
- (NSMutableArray *)prayerTimesDate:(NSDate *)date latitude:(double)latitude longitude:(double)longitude andTimezone:(double)timezone
{
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
return [self getDatePrayerTimesForYear:year month:month day:day latitude:latitude longitude:longitude andtimeZone:timezone];
}
Assuming your prayerTimesDate: method is already returning the expected result, you can loop through each day of the year while repeatedly call prayerTimesDate: to get an array containing the prayer times for each day, ex:
func yearlyPrayerDatesFromCurrentDate (latitude:Double, longitude:Double, timezone:Double) -> NSMutableArray {
// Set "date" to equal the current day
var date:NSDate! = NSDate()
// Increment "date" by one year to calculate the ending
// date for the loop
let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = NSDateComponents()
dateComponents.year = 1
let endingDate:NSDate! = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: nil)
// Create an array to hold *all* the returned
// results for the year
var datesArray = NSMutableArray()
// Loop through each date until the ending date is
// reached
while date.compare(endingDate) != NSComparisonResult.OrderedDescending {
// Call your prayerTimesDate: method on the current
// date to get that date's prayer times and add the
// times from the returned array to the datesArray
datesArray.addObjectsFromArray(prayerTimesDate(date, latitude: latitude, longitude: longitude, andTimezone: timezone))
// increment the date by 1 day
let dateComponents = NSDateComponents()
dateComponents.day = 1
date = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: nil)
}
return datesArray
}
Here is another example for a period over 14 days (without NSCalendar):
let ti:NSTimeInterval = 24*60*60 //one day
let dateFrom = NSDate() //Now
let dateTo = dateFrom.dateByAddingTimeInterval(24*60*60*14) //14 Days later
var nextDate = NSDate()
var endDate = dateTo.dateByAddingTimeInterval(ti)
while nextDate.compare(endDate) == NSComparisonResult.OrderedAscending
{
print("nextDate:", nextDate)
nextDate = nextDate.dateByAddingTimeInterval(ti)
}
Create an NSDateComponents instance for 1 day and NSDate objects for each time on the first day. Now you can iterate over the number of days you want (or until you hit then end date) and then you can use dateByAddingComponents:toDate:options: of the calendar to get the new date for each day.
From Apple doc: To compute a sequence of dates, use the enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock: method instead of calling this method ( - nextDateAfterDate:matchingComponents:options: ) in a loop with the previous loop iteration's result.
As I got, it will iterate all dates that matched with "matchingComponents" till you finish iteration with "stop.memory = true"
//: Playground - noun: a place where people can play
import UIKit
let calendar = NSCalendar.currentCalendar()
let startDate = calendar.startOfDayForDate(NSDate())
let finishDate = calendar.dateByAddingUnit(.Day, value: 10, toDate: startDate, options: [])
let dayComponent = NSDateComponents()
dayComponent.hour = 1
calendar.enumerateDatesStartingAfterDate(startDate, matchingComponents: dayComponent, options: [.MatchStrictly]) { (date, exactMatch, stop) in
print(date)
if date!.compare(finishDate!) == NSComparisonResult.OrderedDescending {
// .memory gets at the value of an UnsafeMutablePointer
stop.memory = true
}
}

UIDatePicker restrict hours but not date

I came across a situation where I needed to restrict a UIDatePicker's selected hour, but still allow free selection of the day. This would be useful if you wanted to allow a user to select a date/time during set business hours. I found something that was close to what I was wanting to do by alerting the user that their selection was bad, but didn't actually change the date on the picker, so I wanted to share my solution Q&A-style.
This particular example will not allow selection of times before 7:00am or after 9:59pm. Selection of an "invalid" time will immediately slide the UIDatePicker back to the closest valid time on the respective end of the spectrum (for example, selection of 10:02pm will immediately slide back to 9:59pm)
- (void)datePickerChanged
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:datePicker.date];
if([components hour] < 7)
{
[components setHour:7];
[components setMinute:0];
[datePicker setDate:[[NSCalendar currentCalendar] dateFromComponents:components]];
}
else if([components hour] > 21)
{
[components setHour:21];
[components setMinute:59];
[datePicker setDate:[[NSCalendar currentCalendar] dateFromComponents:components]];
}
}
Edit: As #DuncanC suggested in the comments, feedback to the user should probably be included, such as a label saying "Only times between 7:00am and 9:59pm can be used"
In Swift2.0:
func datePickerChanged() {
let components = NSCalendar.currentCalendar().components(
[NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second, NSCalendarUnit.Weekday, NSCalendarUnit.WeekdayOrdinal, NSCalendarUnit.WeekOfYear],
fromDate: datePickerInstance.date)
if components.hour < 7 {
components.hour = 7
components.minute = 0
datePickerInstance.setDate(NSCalendar.currentCalendar().dateFromComponents(components)!, animated: true)
}
else if components.hour > 21 {
components.hour = 21
components.minute = 59
datePickerInstance.setDate(NSCalendar.currentCalendar().dateFromComponents(components)!, animated: true)
}
else {
print("Everything is good.")
}
}
If you want to actually limit the hours that are displayed, I built a custom picker for that purpose. It's a subclass of UIPickerView and it replicates the functionality of UIDatePicker in countDownTimer mode, while adding support to set maxTimeInterval.
You use it like this:
GSTimeIntervalPicker *picker = [[GSTimeIntervalPicker alloc] init];
picker.maxTimeInterval = (3600 * 3); // set the limit
picker.minuteInterval = 5; // the step. Default is 1 min.
picker.timeInterval = (3600 * 1.5); // 1 h 30 minutes
picker.onTimeIntervalChanged = ^(NSTimeInterval newTimeInterval) {
// Use the value
};
Available on GitHub under MIT license. Blog post here.
In Swift 4:
func datePickerChanged() {
var components = Calendar.current.dateComponents([.hour, .minute, .month, .year, .day], from: datePicker.date)
if components.hour! < 7 {
components.hour = 7
components.minute = 0
datePicker.setDate(Calendar.current.date(from: components)!, animated: true)
}
else if components.hour! > 21 {
components.hour = 21
components.minute = 59
datePicker.setDate(Calendar.current.date(from: components)!, animated: true)
}
else {
print("Everything is fine!")
}
}

Getting date from weekday

I'm doing this app where the user inputs some days (Using UITableView, monday - sunday).
I then need the app to figure out which dates this matches with. Say it's the user sits on sunday the 15th and chooses monday and tuesday. The app will figure out the dates are monday 16th and tuesday 17th.
How would one go about that using NSDate and such? I know how to find a weekday using the date, but I want the opposite.
Of course it has to be the closest days, like not finding monday the 23rd, but finding 16th.
Hope that makes sense. :-)
A direct method, without using a loop:
NSUInteger targetWeekday = ...; // 1 = Sunday, 2 = Monday, ...
// Date components for today:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
fromDate:now];
// Adjust components for target weekday:
if (targetWeekday >= comp.weekday) {
comp.day += (targetWeekday - comp.weekday);
} else {
comp.day += (targetWeekday + 7 - comp.weekday); // Assuming 7 days per week.
}
comp.weekday = targetWeekday;
// And back to NSDate:
NSDate *targetDate = [cal dateFromComponents:comp];
Remark:
if (targetWeekday >= comp.weekday) {
comp.day += (targetWeekday - comp.weekday);
} else {
comp.day += (targetWeekday + 7 - comp.weekday); // Assuming 7 days per week.
}
can be replaced by the shorter, equivalent code
comp.day += (targetWeekday + 7 - comp.weekday) % 7;
You can do it by following a simple procedure:
Start with an NSDate that represents today
Get the day of the week from it (here is how it is done)
If the day of the week matches what's in the selected UITableViewCell, you are done.
Otherwise, add one day to NSDate (here is how it is done), and go back to step 2.

Resources