How to select multiple dates in TapKu library? - xcode

I would like to show the multiple selected dates in tapkilibrary .like highlight the dates between 14aug2011 to 18aug2011 .

-(NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate{
NSLog(#"Date Selected is %#",date);
//txtbdate.text=date;
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[timeFormat setDateFormat:#"yyyy-MM-dd"];
[timeFormat setTimeZone:gmt];
//[timeFormat setLocale:[NSLocale currentLocale]];
//[timeFormat setTimeZone:[NSTimeZone localTimeZone]];
NSString *theTime = [timeFormat stringFromDate:date];
NSLog(#"%#",theTime);
objappdel.strdate=theTime;
[tkmonthView reload];
AppointmentDetail *appointmentDetail=[[AppointmentDetail alloc]initWithNibName:#"AppointmentDetail" bundle:nil];
[self.navigationController pushViewController:appointmentDetail animated:YES];
[appointmentDetail release];
}
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate
{
NSMutableArray * data = [[NSMutableArray alloc] init];
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateForm setDateFormat:#"yyyy-MM-dd"];
[dateForm setTimeZone:gmt];
NSDate *date ;
for (int i=0; i<[objappdel.arrDate count]; i++)
{
NSString *time;
time=[objappdel.arrDate objectAtIndex:i];
//time= [[[jobData valueForKey:#"Record"] objectAtIndex:i] valueForKey:#"JobStartDate"];
//time = [[time componentsSeparatedByString:#" "] objectAtIndex:0];
date = [dateForm dateFromString:time];
[data addObject:[NSString stringWithFormat:#"%#",date]];
}
NSArray *copy = [data copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
if ([data indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)
{
[data removeObjectAtIndex:index];
}
index--;
}
NSLog(#"sorted dates are %#",copy);
// Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on.
NSMutableArray *marks = [NSMutableArray array];
// Initialise calendar to current type and set the timezone to never have daylight saving
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Construct DateComponents based on startDate so the iterating date can be created.
// Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed
// with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first
// iterating date then times would go up and down based on daylight savings.
NSDateComponents *comp = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
fromDate:startDate];
NSDate *d = [cal dateFromComponents:comp];
// Init offset components to increment days in the loop by one each time
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
// for each date between start date and end date check if they exist in the data array
while (YES) {
// Is the date beyond the last date? If so, exit the loop.
// NSOrderedDescending = the left value is greater than the right
if ([d compare:lastDate] == NSOrderedDescending)
{
break;
}
// If the date is in the data array, add it to the marks array, else don't
//NSLog(#"%#",[d description]);
if ([data containsObject:[d description]]) {
[marks addObject:[NSNumber numberWithBool:YES]];
} else {
[marks addObject:[NSNumber numberWithBool:NO]];
}
// Increment day using offset components (ie, 1 day in this instance)
d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
}
[offsetComponents release];
return [NSArray arrayWithArray:marks];
}
Use this delegate method. It will return an NSArray of dates which you want to highlight.

You can do this by first entering the dates in to an array. code for this is.
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(#"selected Date IS - %#",inDate);
[myArray addObject:d];
for (id entry in myArray)
{
if (inDate == nil && outDate == nil)
{
inDate = d;
outDate = d;
}
if ([d compare:inDate] == NSOrderedAscending)
{
inDate = d;
}
if ([d compare:outDate] == NSOrderedDescending)
{
outDate = d;
}
d = nil;
}
}
After this you have to use a button click action by which you can make the dates selected between these two dates. Code for it is:
- (IBAction)goBtn:(id)sender
{
NSLog(#"startDate is: %#",inDate);
NSLog(#"endDate is: %#",outDate);
[calendar reload];
inDate = nil;
outDate = nil;
}
}
Then in one delegate method you just have to make an array containing all the dates between these two dates. It will be called just after the button click. Code for it is:
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {
//***********
NSMutableArray *tempData = [[NSMutableArray alloc] init];
NSDate *nextDate;
for ( nextDate = inDate ; [nextDate compare:outDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) {
// use date
NSLog(#"%#",nextDate);
[tempData addObject:[NSString stringWithFormat:#"%#",nextDate]];
}
[tempData addObject:[NSString stringWithFormat:#"%#",outDate]];
//***********
NSMutableArray *marks = [NSMutableArray array];
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit |
NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit)
fromDate:startDate];
NSDate *d = [cal dateFromComponents:comp];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
while (YES) {
if ([d compare:lastDate] == NSOrderedDescending) {
break;
}
if ([tempData containsObject:[d description]]) {
[marks addObject:[NSNumber numberWithBool:YES]];
} else {
[marks addObject:[NSNumber numberWithBool:NO]];
}
d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
}
return [NSArray arrayWithArray:marks];
}
I hope, this helped you. Please let me know if you face any problem.

Related

Pause and Resume Time Xcode

I know that there is no way to pause a timer using NSTimer. I know i have to store the date and call it again. I have tried every solution and i cannot find any that have successfully worked. So my question is, does anyone know how to pause and resume?
This worked good for me.
Created 2 UIButtons ('startButton' & 'resetButton'), a UILabel to display time ('timeLabel'), NSTimeInterval ('pauseTimeInterval'), NSTimer (stopWatchTimer') and used the following code:
NSDate *pauseStart, *previousFireDate, *startDate;
NSTimeInterval pauseTimeInterval;
NSTimer *stopWatchTimer;
-(void)pauseTimer{
pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
previousFireDate = [self fireDate];
[self setFireDate:[NSDate distantFuture]];
}
-(void)resumeTimer{
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[self setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}
-(IBAction)startTime:(id)sender {
//start timer
if ([startButton.titleLabel.text isEqualToString:#"Start"] && (![self.stopWatchTimer isValid]) && ([timeLabel.text isEqualToString:#"00:00:00"]))
{
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
resetButton.hidden = YES;
}
//pause timer
else if (([self.stopWatchTimer isValid]) && ([startButton.titleLabel.text isEqualToString:#"Stop"]))
{
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[self.stopWatchTimer pauseTimer];
resetButton.hidden = NO;
}
//resume timer
else {
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
[self.stopWatchTimer resumeTimer];
resetButton.hidden = YES;
}
}
-(IBAction)resetTime:(id)sender {
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
self.timeLabel.text = #"00:00:00";
[startButton setTitle:#"Start" forState:UIControlStateNormal];
pauseTimeInterval = 0.0;
resetButton.hidden = YES;
}
-(void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timeLabel.text = timeString;
pauseTimeInterval = timeInterval;
}

How do I get start date, end date and location of an EKEventStore function

i have this code which reads calendar data from the calendar app.
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
NSError *error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Import" message:#"Import Unavailable" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}];
NSCalendar *calendar = [NSCalendar currentCalendar];
// Create the start date components
NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init];
oneDayAgoComponents.day = -1;
NSDate *oneDayAgo = [calendar dateByAddingComponents:oneDayAgoComponents
toDate:[NSDate date]
options:0];
// Create the end date components
NSDateComponents *oneYearFromNowComponents = [[NSDateComponents alloc] init]; oneYearFromNowComponents.year = 1;
NSDate *oneYearFromNow = [calendar dateByAddingComponents:oneYearFromNowComponents
toDate:[NSDate date]
options:0];
// Create the predicate from the event store's instance method
NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo
endDate:oneYearFromNow
calendars:nil];
// Fetch all events that match the predicate
NSArray *events = [store eventsMatchingPredicate:predicate];
for (id name in events)
NSLog (#"%#", name);
it logs full details of the result which outputs:
EKEvent <0x937c410>
{ title = Meeting w/ David;
location = (null);
calendar = EKCalendar <0x938a650> {title = Calendar; type = Local; allowsModify = YES; color = #1BADF8;};
alarms = (null);
URL = (null);
lastModified = 2014-03-27 11:52:39 +0000;
timeZone = Asia/Manila (GMT+8) offset 28800
};
location = (null);
startDate = 2014-03-28 04:00:00 +0000;
endDate = 2014-03-28 05:00:00 +0000;
allDay = 0;
floating = 0;
recurrence = (null);
attendees = (null)
};
what I want is, I only want to get start date, end date and location on 3 separate arrays..how do I get these?
BITTER BOYS :(
heres the answer to my question:
modified the last code to
NSArray *events = [store eventsMatchingPredicate:predicate];
for (id name in events){
NSString *theName = [name valueForKey:#"title"];
NSLog (#"%#", theName);
//NSLog (#"%#", name);
}

EventKit saveEvent is not working in iOS 7

I have added following code in my application.It is working fine if [comps setYear:1] but if i change year value to 2 or greater than 2 code does not show me any error but also not adding any event in calender. This happens in iOS 7 only. But if I run the same code on iOS 6 , its working correctly & event gets added in calender successfully. Is there any restriction in iOS 7 for adding future events ?
-(void)addEvent{
EKEventStore *es = [[EKEventStore alloc] init];
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
BOOL needsToRequestAccessToEventStore = (authorizationStatus == EKAuthorizationStatusNotDetermined);
if (needsToRequestAccessToEventStore) {
[es requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
[self setEventForStore:es];
} else {
}
}];
} else {
BOOL granted = (authorizationStatus == EKAuthorizationStatusAuthorized);
if (granted) {
[self setEventForStore:es];
} else {
}
}
}
-(void)setEventForStore:(EKEventStore*)store{
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"Event 4";
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
// comps.day =3650;
comps.day=5;
comps.hour=1;
comps.year=2;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
event.startDate = sevenDays;
NSDate *sevenDays1 = [event.startDate dateByAddingTimeInterval:60*60];;
// duration = 1 h
event.endDate = sevenDays1;
[event setCalendar:[store defaultCalendarForNewEvents]];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}
`
Whenever dealing with dates through components, please set them in the following fashion:
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:05];
[comps setMonth:01];
[comps setYear:2014]; //instead of adding a single digit number like so: 2
//followed by your code...
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//...
UPDATE 1
You mentioned that your event is not being saved in the calendar when you slightly adjust the integer values in your NSDate's components. One quick way to see whats happening is by NSLogging your date. See what the ouput is before you try to add it to your calendar.
//Right after this below line
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//Add the code here so we can see what `sevenDays` prints out.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:sevenDays];
NSLog(#"Seven Days date = %#", strDate);

MapKit and adding new pins after a MKLocalSearch

I'm running a MKLocalSearch request and when I find POIs I want to drop a pin based on the coordinates of the POIs I find. NSLog(#"annotations %d",[mapView.annotations count]); returns 0 even with valid coordinates for the POIs
- (void)resultsForButtonTapped:(NSString *)search
{
arrayOfPOIs = [[NSMutableArray alloc] init];
arrayOfAnnotaions = [[NSMutableArray alloc] init];
NSLog(#"%#",search);
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
MKCoordinateRegion region;
request.naturalLanguageQuery = search;
request.region = region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localsearch = [[MKLocalSearch alloc] initWithRequest:request];
[localsearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error != nil) {
return;
}else{
if ([response.mapItems count] == 0) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
for (MKMapItem *item in response.mapItems)
{
NSString *name = item.name;
NSLog(#"%#",name);
[arrayOfPOIs addObject:name];
}
results = response;
NSLog(#"%d",[arrayOfPOIs count]);
for (int i=0; i<[results.mapItems count]; i++) {
MKMapItem* itemPOI = results.mapItems[i];
NSLog(#"Result: %#",itemPOI.placemark.name);
NSLog(#"Result: %#",itemPOI.placemark.name);
MKPlacemark* annotation= [[MKPlacemark alloc] initWithPlacemark:itemPOI.placemark];
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = annotation.coordinate;
[mapView addAnnotation:marker];
NSLog(#"annotations %d",[mapView.annotations count]);
}
[self loadTheDataAgain];
}
}];
// NSLog(#"outside the block, the count is %lu",(unsigned long)[arrayOfPOIs count]);
NSLog(#"stuff %#",arrayOfAnnotaions);
}

date conversion to string xcode

I'm developing an app which displays start date and end date, but I'm having an issue with date displayed on textfield
everything works fine here:
but when I turn to December 30 2012 in output you can read that says 2012 (Hardcoded) but in textfield it writes 2013 (formatted):
happens the same thing if I try using "All day" option:
gonna share my app code as well for making things easier
#import "StartEndEventVC.h"
#import "visitVC.h"
#import "Functions.h"
#interface StartEndEventVC ()
{
NSDate *date;
NSDateFormatter *df;
NSString *selectedCell;
}
#property (nonatomic, strong) Functions *funciones;
#end
#implementation StartEndEventVC
#synthesize funciones = _funciones;
#synthesize datePicker = _datePicker,
SwitchDate = _SwitchDate,
fecFinDateSE = _fecFinDateSE,
fecInicioDateSE = _fecInicioDateSE;
#pragma mark *** Common methods ***
- (void)viewDidLoad
{
[super viewDidLoad];
//Datepicker initial settings
self.datePicker.timeZone = [NSTimeZone localTimeZone];
self.datePicker.locale = [NSLocale currentLocale];
self.datePicker.calendar = [NSCalendar currentCalendar];
//Date format initial settings
df = [NSDateFormatter new];
[df setDateFormat:#"EE, dd MMM YYYY HH:mm a"];
[df setTimeZone:[NSTimeZone localTimeZone]];
//initial cell to interact with datepicker
selectedCell = #"startDate";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(didBack:)];
}
-(void)estableceFechaCamposTexto{
self.fecInicioDateSE = [[NSDate alloc]init];
self.fecFinDateSE = [[NSDate alloc]init];
self.fecInicioDateSE = [NSDate date];
self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60];
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
}
-(void)viewDidAppear:(BOOL)animated{
if ((self.fecInicioDateSE == nil) || (self.fecFinDateSE == nil)) [self estableceFechaCamposTexto];
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
}
-(Functions *)funciones{
if (!_funciones) _funciones = [[Functions alloc]init];
return _funciones;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"doneStartEnd"]) {
[segue.destinationViewController setFecInicioDateV: self.fecInicioDateSE];
[segue.destinationViewController setFecFinDateV: self.fecFinDateSE];
NSLog(#"fecha inicio StartEvent: %#", self.fecInicioDateSE);
NSLog(#"fecha fin StartEvent: %#", self.fecFinDateSE);
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.row) {
case 0:
selectedCell = #"startDate";
self.datePicker.date = self.fecInicioDateSE;
break;
case 1:
selectedCell = #"endDate";
self.datePicker.date = self.fecFinDateSE;
default:
break;
}
}
#pragma mark -
#pragma mark *** Custom methods ***
-(void)comparaFechaInicio{
if ([self.fecInicioDateSE timeIntervalSinceDate:self.fecFinDateSE] >= 0) {
if (self.SwitchDate.on) self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60*24];
else
if(!(self.SwitchDate.on)) self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60];
}
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
NSLog(#"Hardcoded date: %#", self.fecInicioDateSE);
NSLog(#"formatted date: %#", [df stringFromDate:self.fecFinDateSE]);
}
- (void) didBack:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark *** Button actions ***
-(IBAction)adjustDate:(id)sender{
if ([selectedCell isEqualToString:#"startDate"]){
self.fecInicioDateSE = [self.datePicker date];
[self comparaFechaInicio];
}
else
if ([selectedCell isEqualToString:#"endDate"]){
self.fecFinDateSE = [self.datePicker date];
self.endDateLabel.text = [df stringFromDate:self.datePicker.date];
}
}
- (IBAction)saveChanges:(id)sender {
[self comparaFechaInicio];
[self performSegueWithIdentifier:#"doneStartEnd" sender:self];
}
-(IBAction)changeDateType:(id)sender{
if (self.SwitchDate.on){
self.datePicker.datePickerMode = UIDatePickerModeDate;
[df setDateFormat:#"EE, dd MMM YYYY"];
}
else{
self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
[df setDateFormat: #"EE, dd MMM YYYY HH:mm a"];
}
[self comparaFechaInicio];
}
#pragma mark -
#end
You fell in the same trap that Apple did with recent their Do Not Disturb bug. You want to use yyyy in your NSDateFormatter, not YYYY.

Resources