I having an app so i just added some event or remainder (football match,movie) in my app for some particular date and time.
And this add event i also want to display in iphone calendar.
thanks and regards.
Have you checked out EventKit?
You can use simple JTCalender for this
first oyu have to include JT Calender framework for the project
You have to create two views in your UIViewController:
The first view is JTCalendarMenuView and it represents the part with the months names. This view is optional.
The second view is JTHorizontalCalendarView or JTVerticalCalendarView, it represents the calendar itself.
Your UIViewController have to implement JTCalendarDelegate, all methods are optional.
in .h file
#import <UIKit/UIKit.h>
#import "CustomTableViewCell.h"
#import "JTCalendar/JTCalendar.h"
#interface CalendarViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,JTCalendarDelegate>
#property (strong, nonatomic) JTCalendarMenuView *calendarMenuView;
#property (strong, nonatomic) JTHorizontalCalendarView *calendarContentView;
#property (strong, nonatomic) JTCalendarManager *calendarManager;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarContentViewHeight;
#end
.m file
------------
#import "CalendarViewController.h"
#import "ApptWindowView.h"
#import "SVProgressHUD.h"
#interface CalendarViewController () < UITextFieldDelegate>{
NSMutableDictionary *dayDateDict;
NSMutableArray*jsonDate,*dateAr1,*dateAr2;
UITableView *appointTableView;
CGSize screenRect;
NSString *dateAfterString;
int fontSize,headerBtnfont,height;
NSDateFormatter *dateFormat1 ;
NSString*cmpDay;
int count;
NSString * clickedDate;
NSString *day ;
NSMutableDictionary *_eventsByDate;
NSDate *_todayDate;
NSDate *_minDate;
NSDate *_maxDate;
NSDate *_dateSelected;
UIActivityIndicatorView *activityIndicator;
int i;
}
#end
#implementation CalendarViewController
- (void)viewDidLoad
{
[super viewDidLoad];
i=0;
dayDateDict=[[NSMutableDictionary alloc]init];
dateAr1=[[NSMutableArray alloc]init];
dateAr2=[[NSMutableArray alloc]init];
screenRect=[[UIScreen mainScreen]bounds].size;
//Create header here
self.view.backgroundColor=[UIColor colorWithRed:(CGFloat)233/255 green:(CGFloat)239/255 blue:(CGFloat)239/255 alpha:1];
UIView * headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 55)];
headerView.backgroundColor =[UIColor whiteColor];
[self.view addSubview:headerView];
UILabel * titleLable =[[UILabel alloc]initWithFrame:CGRectMake(60, 25, [UIScreen mainScreen].bounds.size.width-120, 25)];
titleLable.text =#"CHOOSE APPOINTMENT";
titleLable.textAlignment = NSTextAlignmentCenter;
titleLable.font =[UIFont systemFontOfSize:12];
[headerView addSubview:titleLable];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:[UIImage imageNamed:#"back_btn.png"] forState:UIControlStateNormal];
[backButton setFrame:CGRectMake(15, 30, 45, 15)];
[backButton addTarget:self action:#selector(backAction) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:backButton];
UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
[nextButton setImage:[UIImage imageNamed:#"next_btn.png"] forState:UIControlStateNormal];
[nextButton setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-60, 30, 45, 15)];
[nextButton addTarget:self action:#selector(continueAction) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:nextButton];
[self activityAction];
dispatch_async(dispatch_get_global_queue(0, 0),^{
dispatch_async(dispatch_get_main_queue(),^{
// [self createUI];
[self fetchSchedule];
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
[self createMinAndMaxDate];
_calendarContentView=[JTHorizontalCalendarView new];
_calendarContentView.frame = CGRectMake(20, 100,[UIScreen mainScreen].bounds.size.width-40 , [UIScreen mainScreen].bounds.size.width-40);
_calendarContentView.backgroundColor=[UIColor whiteColor];
[_calendarManager setContentView:_calendarContentView];
[self.view addSubview:_calendarContentView];
_calendarMenuView=[JTCalendarMenuView new];
_calendarMenuView.frame=CGRectMake(20, 55,[UIScreen mainScreen].bounds.size.width-40 ,50);
_calendarMenuView.backgroundColor=[UIColor clearColor];
[self.view addSubview:_calendarMenuView];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setDate:[NSDate date]];
[activityIndicator stopAnimating];
});
});
[self createUI];
}
-(void)continueAction{
ApptWindowView *apptWindow=[[ApptWindowView alloc]init];
[self.navigationController pushViewController:apptWindow animated:YES];
}
- (UIView<JTCalendarDay> *)calendarBuildDayView:(JTCalendarManager *)calendar
{
JTCalendarDayView *view = [JTCalendarDayView new];
view.textLabel.font = [UIFont fontWithName:#"Avenir-Light" size:13];
view.textLabel.textColor = [UIColor blackColor];
return view;
}
NSError *error; NSURLResponse * urlResponse;
NSURL * url =[NSURL URLWithString:fetchScheduleService];
NSMutableURLRequest * request =[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:50];
NSString * body =[NSString stringWithFormat:#"departmentId=%d",[SingletonClass sharedSingleton].deptId ];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData * data =[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (!data) {
[SVProgressHUD dismiss];
return;
}
id jsonResponse =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"schedule jason---->%#",jsonResponse);
if ([[jsonResponse objectForKey:#"code"] isEqualToNumber:[NSNumber numberWithInt:200]]) {
jsonDate=[jsonResponse objectForKey:#"data"];
[self convertTimeStamp];
}
//dispatch_async(dispatch_get_main_queue(),^{
// [SVProgressHUD dismiss];
//[self createUI];
// });
// });
}
#pragma mark-Create UI/Table View
-(void)createUI{
appointTableView = [[UITableView alloc]init];
appointTableView.frame = CGRectMake(10, 100+screenRect.width-40+10, screenRect.width-20, screenRect.height-( 100+screenRect.width-40+10));
appointTableView.delegate = self;
appointTableView.dataSource = self;
appointTableView.backgroundColor =[UIColor clearColor];
appointTableView.showsVerticalScrollIndicator = NO;
appointTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:appointTableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[dayDateDict objectForKey:clickedDate] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell * cell =(CustomTableViewCell*) [tableView cellForRowAtIndexPath:indexPath];
if (!cell) {
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"calender"];
cell.backgroundColor = [UIColor clearColor];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[dateFormat1 setDateFormat:#"HH:mm"];
NSDate * aptTime =[dateFormat1 dateFromString:[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row] ];
NSDate *dateAfter=[aptTime dateByAddingTimeInterval:(1800) ];
dateAfterString =[dateFormat1 stringFromDate:dateAfter];
NSString *dis=[NSString stringWithFormat:#"%#-%#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row],dateAfterString];
cell.appointmentTime.text =dis;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return 100;
}
return 60;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
ApptWindowView *apptWindow=[[ApptWindowView alloc]init];
[self.navigationController pushViewController:apptWindow animated:YES];
NSLog(#"clicked date-->%#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row]);
NSDate * aptTime =[dateFormat1 dateFromString:[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row] ];
NSDate *dateAfter=[aptTime dateByAddingTimeInterval:(1800) ];
dateAfterString =[dateFormat1 stringFromDate:dateAfter];
NSString *dis=[NSString stringWithFormat:#"%# to %# on %#",[[dayDateDict objectForKey:clickedDate]objectAtIndex:indexPath.row],dateAfterString,day];
[[NSUserDefaults standardUserDefaults]setObject:dis forKey:#"appointmentTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
#pragma mark-convert timeStamp to date
-(void)convertTimeStamp{
for( NSString*valueForDate in jsonDate){
NSTimeInterval timeSec=[valueForDate doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeSec];
NSLog(#"\ndate are-->%#",date);
[self separateDate:date];
}
}
#pragma mark-separate date and Time
-(void)separateDate:(NSDate*)date1{
dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"HH:mm"];
NSString * resultTime =[dateFormat1 stringFromDate:date1];
NSLog(#"date is-->%#",resultTime);
[dateFormat1 setDateFormat:#"dd-MM-YYYY"];
NSString *resultDay=[dateFormat1 stringFromDate:date1];
NSLog(#"day is-->%#",resultDay);
if([cmpDay isEqual:resultDay] || cmpDay==nil){
if(count!=1){
[dateAr1 addObject:resultTime];
}
if(count==1){
[dateAr2 addObject:resultTime];
}
}
else{
count=1;
dateAr2=[[NSMutableArray alloc]init];
[dateAr2 addObject:resultTime];
}
cmpDay=resultDay;
if(count!=1){
[dayDateDict setObject:dateAr1 forKey:resultDay];
}
else{
[dayDateDict setObject:dateAr2 forKey:resultDay];
}
NSLog(#"dictionary--->%#",dayDateDict);
}
#pragma mark - Buttons callback
- (IBAction)didGoTodayTouch
{
[_calendarManager setDate:_todayDate];
}
- (IBAction)didChangeModeTouch
{
_calendarManager.settings.weekModeEnabled = !_calendarManager.settings.weekModeEnabled;
[_calendarManager reload];
CGFloat newHeight = 300;
if(_calendarManager.settings.weekModeEnabled){
newHeight = 85.;
}
self.calendarContentViewHeight.constant = newHeight;
[self.view layoutIfNeeded];
}
#pragma mark - CalendarManager delegate
// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
// Today
if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor blueColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Selected date
else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
// Another day of the current month
else{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
if([self haveEventForDay:dayView.date]){
dayView.dotView.hidden = NO;
}
else{
dayView.dotView.hidden = YES;
}
}
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
_dateSelected = dayView.date ;
NSLog(#"orginal Clicked day-->%#",dayView.date);
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:#"dd-MM-YYYY"];
clickedDate =[dateFormat2 stringFromDate:_dateSelected];
NSLog(#"Selected date===>%#",clickedDate);
NSString* s= [dayDateDict objectForKey:clickedDate];
NSLog(#"time is===>%#",s);
[dateFormat2 setDateFormat:#"EEE, MMM dd "];
day =[dateFormat2 stringFromDate:_dateSelected];
NSLog(#"Selected day===>%#",day);
// Animation for the circleView
dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
[UIView transitionWithView:dayView
duration:.3
options:0
animations:^{
dayView.circleView.transform = CGAffineTransformIdentity;
[_calendarManager reload];
} completion:nil];
// Load the previous or next page if touch a day from another month
if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
[_calendarContentView loadNextPageWithAnimation];
}
else{
[_calendarContentView loadPreviousPageWithAnimation];
}
}
[appointTableView reloadData];
}
#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}
- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
// NSLog(#"Next page loaded");
}
- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
// NSLog(#"Previous page loaded");
}
#pragma mark - Fake data
- (void)createMinAndMaxDate
{
_todayDate = [NSDate date];
// Min date will be 2 month before today
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-3];
// Max date will be 2 month after today
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:3];
}
- (BOOL)haveEventForDay:(NSDate *)date
{
if(i>=[dayDateDict allKeys].count){
i=0;
}
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *key = [dateFormatter stringFromDate:date];
while(i<[dayDateDict allKeys].count){
if([key isEqual:[[dayDateDict allKeys]objectAtIndex:i]]){
i++;
return YES;
}
else
return NO;
}
return NO;
}
#pragma mark-Activity Indicator
-(void)activityAction{
CGSize windowSize =[UIScreen mainScreen].bounds.size;
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.frame = CGRectMake(windowSize.width/2-20, windowSize.height/2-55,40 ,40);
activityIndicator.color = [UIColor blackColor];
activityIndicator.alpha = 1;
[self.view addSubview:activityIndicator];
//[self placeSearchbaseId];
[activityIndicator startAnimating];
}
#end
I am fetching json data feching time form json as time stamp format and converting to local time
Then i am creating an events for it in the calender
You have third party apps like Kal which supports calendar integration. Check this link:
Kal Calendar
Hope it helps
Related
I am using 3 view on one UIViewController. Because of this I have lots of code in viewDidLoad() Like this:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
customActivityIndicator.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"tmp-0.gif"],[UIImage imageNamed:#"tmp-1.gif"],[UIImage imageNamed:#"tmp-2.gif"],[UIImage imageNamed:#"tmp-3.gif"],[UIImage imageNamed:#"tmp-4.gif"],[UIImage imageNamed:#"tmp-5.gif"],[UIImage imageNamed:#"tmp-6.gif"],[UIImage imageNamed:#"tmp-7.gif"],[UIImage imageNamed:#"tmp-8.gif"],[UIImage imageNamed:#"tmp-9.gif"],[UIImage imageNamed:#"tmp-10.gif"],[UIImage imageNamed:#"tmp-11.gif"],[UIImage imageNamed:#"tmp-12.gif"],[UIImage imageNamed:#"tmp-13.gif"],[UIImage imageNamed:#"tmp-14.gif"],[UIImage imageNamed:#"tmp-15.gif"],nil];
customActivityIndicator.animationDuration = 1.0; // in seconds
customActivityIndicator.animationRepeatCount = 0; // sets to loop
[customActivityIndicator startAnimating];
btn.hidden=YES;
UILabel *lab =[[UILabel alloc] init];
lab.text = [NSString awesomeIcon:FaMailReply];
UIImage *listImage2 = [UIImage imageNamed:#"backicon.png.png"];
UIButton *listButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton2.backgroundColor=[UIColor whiteColor];
[[listButton2 layer] setBorderWidth:0.5f];
listButton2.layer.borderColor =[[UIColor blackColor] CGColor];
listButton2.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton2.clipsToBounds = YES;
UIFont *font = [UIFont fontWithName:#"FontAwesome" size:15.0];
UIColor *color = [UIColor blueColor];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithString:lab.text attributes:attrsDictionary];
// get the image size and apply it to the button frame
CGRect listButton2Frame = listButton2.frame;
listButton2Frame.size = listImage2.size;
listButton2.frame = listButton2Frame;
[listButton2 setAttributedTitle:attributedStr forState:UIControlStateNormal];
[listButton2 addTarget:self
action:#selector(LogoutClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton2 =
[[UIBarButtonItem alloc] initWithCustomView:listButton2];
//Notificaation Icon Button...
UILabel *lablnotification =[[UILabel alloc] init];
// lab.font = [UIFont fontWithName:#"FontAwesome" size:8];
// lab.textColor = [UIColor whiteColor];
lablnotification.text = [NSString awesomeIcon:FaHome];
UIImage *listImage4 = [UIImage imageNamed:#"notification.png"];
UIButton *listButton4 = [UIButton buttonWithType:UIButtonTypeCustom];
listButton4.backgroundColor=[UIColor whiteColor];
[[listButton4 layer] setBorderWidth:0.5f];
listButton4.layer.borderColor =[[UIColor blackColor] CGColor];
listButton4.layer.cornerRadius = btn.bounds.size.width / 3.4;// this value vary as per your desire
listButton4.clipsToBounds = YES;
UIFont *fontnotification = [UIFont fontWithName:#"FontAwesome" size:18.0];
UIColor *colornotification = [UIColor blueColor];
NSDictionary *attrsDictionarynotification = [NSDictionary dictionaryWithObjectsAndKeys:fontnotification,NSFontAttributeName,colornotification,NSForegroundColorAttributeName, nil];
// [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,color,NSForegroundColorAttributeName, nil];
NSAttributedString *attributedStrnotification = [[NSAttributedString alloc] initWithString:lablnotification.text attributes:attrsDictionarynotification];
// get the image size and apply it to the button frame
CGRect listButton4Frame = listButton4.frame;
listButton4Frame.size = listImage4.size;
listButton4.frame = listButton4Frame;
[listButton4 setAttributedTitle:attributedStrnotification forState:UIControlStateNormal];
[listButton4 addTarget:self
action:#selector(ActualNotificationClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton4 =
[[UIBarButtonItem alloc] initWithCustomView:listButton4];
UIImage *listImage3 = [UIImage imageNamed:#"ec2.png"];
UIButton *listButton3 = [UIButton buttonWithType:UIButtonTypeCustom];
// get the image size and apply it to the button frame
CGRect listButton3Frame = listButton3.frame;
listButton3Frame.size = listImage3.size;
listButton3.frame = listButton3Frame;
[listButton3 setImage:listImage3 forState:UIControlStateNormal];
[listButton3 addTarget:self
action:#selector(EmployeeClick:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton3 =
[[UIBarButtonItem alloc] initWithCustomView:listButton3];
self.navigationItem.rightBarButtonItems= [NSArray arrayWithObjects:jobsButton2,jobsButton4, nil];
self.navigationItem.leftBarButtonItems=[NSArray arrayWithObjects:jobsButton3, nil];
//NSUserDefault...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
userid = [defaults objectForKey:#"UserId"];
NSLog(#"User Id is =%#",userid);
ServerString=[defaults objectForKey:#"ServerString"];
DefaultRegionIDString=[defaults objectForKey:#"DefaultRegionIDString"];
DefaultBranchIDString=[defaults objectForKey:#"DefaultBranchIDString"];
DefaultSiteIDString=[defaults objectForKey:#"DefaultSiteIDString"];
DefaultLocationString=[defaults objectForKey:#"DefaultLocationString"];
DefaultDateString =[defaults objectForKey:#"DefaultDateString"];
DefaultTimeString =[defaults objectForKey:#"DefaultTimeString"];
DefaultEmployeeNameString=[defaults objectForKey:#"DefaultEmployeeNameString"];
DefaultRegionNameString=[defaults objectForKey:#"DefaultRegionNameString"];
DefaultBranchNameString=[defaults objectForKey:#"DefaultBranchNameString"];
DefaultSiteNameString=[defaults objectForKey:#"DefaultSiteNameString"];
DefaultEventTypeString=[defaults objectForKey:#"DefaultEventTypeString"];
DefaultIncidentTypeString=[defaults objectForKey:#"DefaultIncidentTypeString"];
DefaultsIncidentNameString=[defaults objectForKey:#"DefaultsIncidentNameString"];
SegmentStringCheck=[defaults objectForKey:#"SegmentStringCheck"];
CheckIncidentString=[defaults objectForKey:#"CheckIncidentString"];
if([DefaultEventTypeString isEqualToString:#"1"])
{
lblreportregion.text = DefaultRegionIDString;
lblreportbranch.text = DefaultBranchIDString;
lblreportsite.text = DefaultSiteIDString;
// lblreportinjurytype.text=DefaultIncidentTypeString;
txtreportlocation.text = DefaultLocationString;
txtreportdate.text = DefaultDateString;
txtreporttime.text = DefaultTimeString;
txtreportemp.text = DefaultEmployeeNameString;
txtreportregion.text=DefaultRegionNameString;
txtreportbranch.text=DefaultBranchNameString;
txtreportsite.text=DefaultSiteNameString;
// txtreportinjurytype.text = DefaultsIncidentNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"2"])
{
lblnearregion.text = DefaultRegionIDString;
lblnearbranch.text = DefaultBranchIDString;
lblnearsite.text = DefaultSiteIDString;
txtnearlocation.text = DefaultLocationString;
txtneardate.text = DefaultDateString;
txtneartime.text = DefaultTimeString;
txtnearemp.text = DefaultEmployeeNameString;
txtnearregion.text=DefaultRegionNameString;
txtnearbranch.text=DefaultBranchNameString;
txtnearsite.text=DefaultSiteNameString;
}
else if ([DefaultEventTypeString isEqualToString:#"3"])
{
lblspotingregion.text = DefaultRegionIDString;
lblspotingbranch.text = DefaultBranchIDString;
lblspotingsite.text = DefaultSiteIDString;
txtspotinglocation.text = DefaultLocationString;
txtspotingdate.text = DefaultDateString;
txtspotingtime.text = DefaultTimeString;
txtsportingemp.text = DefaultEmployeeNameString;
txtspotingregion.text=DefaultRegionNameString;
txtspotingbranch.text=DefaultBranchNameString;
txtspotingsite.text=DefaultSiteNameString;
}
if([SegmentStringCheck isEqualToString:#"0"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
else if ([SegmentStringCheck isEqualToString:#"1"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 1;
viewspoting.hidden=YES;
viewnear.hidden=NO;
viewreport.hidden=YES;
//Near...
[self nearserverconnection];
[self nearserverconnectionincident];
[self nearserverconnectionactivity];
}
else if ([SegmentStringCheck isEqualToString:#"2"])
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 2;
viewspoting.hidden=YES;
viewnear.hidden=YES;
viewreport.hidden=NO;
//Report...
[self reportserverconnection];
[self reportserverconnectioninjury];
}
else
{
segment.selectedSegmentIndex = UISegmentedControlNoSegment;
segment.selectedSegmentIndex = 0;
viewspoting.hidden=NO;
viewnear.hidden=YES;
viewreport.hidden=YES;
}
//.........................//
//Sporting Hide Code...
//Table...
tablesportingbranch.hidden=YES;
tablesportingregion.hidden=YES;
tablesportingsite.hidden=YES;
//Label...
lblsportingactivitytype.hidden=YES;
lblsportingdept.hidden=YES;
lblsportingemp.hidden=YES;
lblspotingbranch.hidden=YES;
lblspotingincidenttype.hidden=YES;
lblspotingregion.hidden=YES;
lblspotingsite.hidden=YES;
//TextFieldDelegate...
txtspotingsite.delegate=self;
txtsportingemp.delegate=self;
txtspotinglocation.delegate=self;
//Date Picker...
pickerspotingdate.hidden=YES;
pickerspotingtime.hidden=YES;
//............................//
//Near Hide Code...
//View...
// viewnear.hidden=YES;
//Table...
tablenearbranch.hidden=YES;
tablenearregion.hidden=YES;
tablenearsite.hidden=YES;
//Label...
lblnearactivitytype.hidden=YES;
lblnearbranch.hidden=YES;
lblneardept.hidden=YES;
lblnearemp.hidden=YES;
lblnearincidenttype.hidden=YES;
lblnearregion.hidden=YES;
lblnearsite.hidden=YES;
//TextFieldDelegate..
txtnearsite.delegate=self;
txtnearemp.delegate=self;
txtnearlocation.delegate=self;
//Date Picker...
pickerneardate.hidden=YES;
pickerneartime.hidden=YES;
//...........................//
//Report Hide View Code...
//View...
// viewreport.hidden=YES;
//Table...
tablereportbranch.hidden=YES;
tablereportinjurytype.hidden=YES;
tablereportregion.hidden=YES;
tablereportsite.hidden=YES;
//Label...
lblreportbranch.hidden=YES;
lblreportdept.hidden=YES;
lblreportemp.hidden=YES;
lblreportinjurytype.hidden=YES;
lblreportregion.hidden=YES;
lblreportsite.hidden=YES;
//TextFieldDelegate...
txtreportsite.delegate=self;
txtreportemp.delegate=self;
txtreportlocation.delegate=self;
//Date Picker...
pickerreporttime.hidden=YES;
pickereportdate.hidden=YES;
//.............................//
//Font Asowme
//Show...
lblspotingShow.font = [UIFont fontWithName:#"FontAwesome" size:15];
lblspotingShow.textColor = [UIColor blackColor];
lblspotingShow.text = [NSString awesomeIcon:FaEye];
//Scroll View...
[scrollspoting setContentSize:CGSizeMake(300, 500)];
[scrollnear setContentSize:CGSizeMake(300, 500)];
[scrollreport setContentSize:CGSizeMake(300, 730)];
UISwipeGestureRecognizer *gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[gestureRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:gestureRecognizer];
//Button Diamiter...
//Spoting Button...
btnsportinghideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnsportinghideadd.clipsToBounds = YES;
//Near Button...
btnnearhideadd.layer.cornerRadius = 4; // this value vary as per your desire
btnnearhideadd.clipsToBounds = YES;
//Report Button...
btnreportnext.layer.cornerRadius = 4; // this value vary as per your desire
btnreportnext.clipsToBounds = YES;
//Spoting...
[self spotingserverconnection];
[self spotingserverconnectionactivity];
[self spotingserverconnectionincident];
[txtspotingsite addTarget:self action:#selector(spotingtextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
// prevents the scroll view from swallowing up the touch event of child buttons
[txtnearsite addTarget:self action:#selector(neartextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
[txtreportsite addTarget:self action:#selector(reporttextFieldDidChangeSite:) forControlEvents:UIControlEventEditingChanged];
UITapGestureRecognizer *tapGesturereportinjury = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideSubViewreportinjury)];
// prevents the scroll view from swallowing up the touch event of child buttons
tapGesturereportinjury.cancelsTouchesInView = NO;
[scrollreport addGestureRecognizer:tapGesturereportinjury];
IssueSelectedIDarray=[[NSMutableArray alloc] init];
IssueSelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedNamearray=[[NSMutableArray alloc] init];
ReportInjurySelectedIDarray=[[NSMutableArray alloc] init];
[self testInternetConnection];
//Spoting Date and Time..
NSDateFormatter *Spotingdateformatter;
Spotingdateformatter = [[NSDateFormatter alloc] init];
[Spotingdateformatter setDateFormat:#"dd/MM/yyyy"];
SpotingdateString = [Spotingdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",SpotingdateString);
CurrentDate=SpotingdateString;
NSDate * now = [NSDate date];
NSDateFormatter *Spotingtimeformatter = [[NSDateFormatter alloc] init];
[Spotingtimeformatter setDateFormat:#"hh:mm"];
SpotingTimeString = [Spotingtimeformatter stringFromDate:now];
NSLog(#"newDateString %#", SpotingTimeString);
//Near Date and Time..
NSDateFormatter *Neardateformatter;
Neardateformatter = [[NSDateFormatter alloc] init];
[Neardateformatter setDateFormat:#"dd/MM/yyyy"];
NeardateString = [Neardateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",NeardateString);
NSDate * nowNear = [NSDate date];
NSDateFormatter *Neartimeformatter = [[NSDateFormatter alloc] init];
[Neartimeformatter setDateFormat:#"hh:mm"];
NearTimeString = [Neartimeformatter stringFromDate:nowNear];
NSLog(#"newDateString %#", NearTimeString);
//Report Date and Time..
NSDateFormatter *Reportdateformatter;
Reportdateformatter = [[NSDateFormatter alloc] init];
[Reportdateformatter setDateFormat:#"dd/MM/yyyy"];
ReportdateString = [Reportdateformatter stringFromDate:[NSDate date]];
NSLog(#"Current Time =%#",ReportdateString);
NSDate * nowReport = [NSDate date];
NSDateFormatter *Reporttimeformatter = [[NSDateFormatter alloc] init];
[Reporttimeformatter setDateFormat:#"hh:mm"];
ReportTimeString = [Reporttimeformatter stringFromDate:nowReport];
NSLog(#"newDateString %#", ReportTimeString);
}
Its working to much slow. Is there is any way to speed it up?
ViewName *Incedent =[[ViewName alloc] initWithNibName:#"ViewName" bundle:nil];
[self.navigationController pushViewController:Incedent animated:YES];
I have used this code to pushviewcontroller.
You need to evaluate what your code is doing, and find out where it is slow. I don't know what this method is doing, but I'm betting the line:
[self testInternetConnection];
is one of the problems. Comment out that line, and see what happens.
I had a problem to retrieve data using realm. What i wanna do is caching the data so that i can use it when user first load the app or user does not have internet connection. Below is the logic what i wanna do.
request from fb api -> fb return 10 data -> display returned data and cache returned data -> if user doesn't have internet connection display cache data or if user have internet connection fetch new data.
below is my code :
FBVideo.h
#import <Realm/Realm.h>
#interface FBVideo : RLMObject
#property (nonatomic, strong) NSString *pageBefore;
#property (nonatomic, strong) NSString *pageAfter;
#property (nonatomic, strong) NSString *thumbnailsURI;
#property (nonatomic, strong) NSString *titleDescription;
#property NSString *id;
#end
FBVideo.m
#import "FBVideo.h"
#implementation FBVideo
+ (NSString *)primaryKey {
return #"id";
}
// Specify default values for properties
+ (NSDictionary *)defaultPropertyValues {
return #{#"pageBefore":#"", #"pageAfter":#"", #"thumbnailsURI":#"", #"titleDescription":#""};
}
+ (NSArray *)ignoredProperties {
return #[];
}
#end
PageVideosCVC.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "FBVideo.h"
#interface PageVideosCVC : UICollectionViewController
#property (strong, nonatomic) NSMutableArray *videoArray;
#property (strong, nonatomic) NSString *pageID;
#property (strong, nonatomic) NSString *pageName;
#property (strong, nonatomic) MPMoviePlayerController *playerController;
#property (assign, nonatomic) CATransform3D initialTransformation;
#property (nonatomic, strong) NSMutableSet *shownIndexes;
//#property (strong, nonatomic) FBVideo *fbVideoRealm;
#end
PageVideosCVC.m
#import "PageVideosCVC.h"
#import "facebook.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import <AFNetworking/AFNetworking.h>
#import <AVFoundation/AVFoundation.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <QuartzCore/QuartzCore.h>
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#interface PageVideosCVC () <UICollectionViewDataSource,UICollectionViewDelegate> {
NSString *pageBefore;
NSString *pageAfter;
NSString *thumbnailsURI;
Reachability *internetReachable;
NSDictionary *videoInfoToSaveInRealm;
// RLMResults *videoResultsFrom
}
#end
#implementation PageVideosCVC
#synthesize videoArray;
static NSString * const reuseIdentifier = #"Cell";
- (void) viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
videoArray = [NSMutableArray array];
/* Make a card effect, rotate the angle of the collectionviewcell to -15
1) Start with an identity transform, which is a fancy math term for “do nothing.”
2) Call CATransform3DRotate to apply a rotation of -15 degrees (in radians), where the negative value indicates a clockwise rotation.
3) Apply the rotation around the axis 0.0, 0.0, 1.0; this represents the z-axis, where x=0, y=0, and z=1.
4) Applying just the rotation to the card isn’t enough, as this simply rotates the card about its center. To make it look like it’s tipped over on a corner, add a translation or shift where the negative values indicate a shift up and to the left.
*/
CGFloat rotationAngleDegrees = -15;
CGFloat rotationAngleRadians = rotationAngleDegrees * (M_PI/180);
CGPoint offsetPositioning = CGPointMake(-20, -20);
CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DRotate(transform, rotationAngleRadians, 0.0, 0.0, 1.0);
transform = CATransform3DTranslate(transform, offsetPositioning.x, offsetPositioning.y, 0.0);
_initialTransformation = transform;
_shownIndexes = [NSMutableSet set];
}
- (void)viewWillAppear:(BOOL)animated {
UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
navBar.barTintColor = UIColorFromRGB(0x266593);
// Altering the font style of the navigation bar title
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[[UINavigationBar appearance] setTranslucent:NO];
[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
shadow, NSShadowAttributeName,
[UIFont fontWithName:#"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
[self.view addSubview: navBar];
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"Down Arrow.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(backButtonTapped:)];
// UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:#"Back"
// style:UIBarButtonItemStylePlain
// target:self
// action:#selector(backButtonTapped:)];
[cancelItem setTintColor:[UIColor whiteColor]];
// UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:#"Done"
// style:UIBarButtonItemStyleBordered
// target:self action:nil];
NSString *selectedPageName = [[NSString alloc] initWithFormat:#"%#", self.pageName];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:selectedPageName];
// navItem.rightBarButtonItem = doneItem;
navItem.leftBarButtonItem = cancelItem;
navBar.items = [NSArray arrayWithObjects: navItem,nil];
[UIBarButtonItem appearance].tintColor = [UIColor blueColor];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self loadVideo:#"a" pagesID:self.pageID];
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if ([pageBefore isEqual:pageBefore]) {
return videoArray.count;
}
return videoArray.count + 1;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == [videoArray count] - 1) {
NSLog(#"page after : %#", pageAfter);
[self loadVideo:pageAfter pagesID:self.pageID];
}
if (![self.shownIndexes containsObject:indexPath]) {
[self.shownIndexes addObject:indexPath];
// Transform collectionviewcell layer
UIView *card = [(UICollectionViewCell*)cell contentView];
card.layer.transform = self.initialTransformation;
card.layer.opacity = 0.5;
[UIView animateWithDuration:0.5 animations:^{
card.layer.transform = CATransform3DIdentity;
card.layer.opacity = 1;
}];
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
__weak typeof(self) weakSelf = self;
if (indexPath.row == [videoArray count]) {
NSLog(#"this is last cell, later make it UIActivityIndicatorView");
} else {
// RLMResults *objects;
//
// objects = [FBVideo allObjects];
// FBVideo *fbVideoRealm = objects[indexPath.row];
//
// UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
// NSURL *thumbnailImage = [NSURL URLWithString:fbVideoRealm.thumbnailsURI];
// [imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
//
// UILabel *titleDescription = (UILabel *)[cell viewWithTag:10];
// titleDescription.text = fbVideoRealm.titleDescription;
NSDictionary *videoData = weakSelf.videoArray[indexPath.row];
NSDictionary *videoThumbnails = [videoData valueForKey:#"thumbnails"];
NSArray *thumbnailsData = [videoThumbnails objectForKey:#"data"][0];
thumbnailsURI = [thumbnailsData valueForKey:#"uri"];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:100];
NSURL *thumbnailImage = [NSURL URLWithString:thumbnailsURI];
[imgView sd_setImageWithURL:thumbnailImage placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
UILabel *titleDescription = (UILabel *)[cell viewWithTag:10];
titleDescription.text = videoData[#"description"];
}
return cell;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *videoSource = videoArray[indexPath.row];
NSURL *videoURL = [NSURL URLWithString:[videoSource valueForKey:#"source"]];
self.playerController = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
[[self.playerController view] setFrame:[self.view bounds]]; // Frame must match parent view
[self.view addSubview:[self.playerController view]];
self.playerController.movieSourceType = MPMovieSourceTypeStreaming;
self.playerController.controlStyle = MPMovieControlStyleFullscreen;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doneButtonClick:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.playerController play];
// Play the video using AVPlayer iOS9 above
// AVPlayer *player = [AVPlayer playerWithURL:videoURL];
// AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
// playerLayer.frame = self.view.bounds;
// [self.view.layer addSublayer:playerLayer];
// [player play];
}
- (void)doneButtonClick:(NSNotification*)aNotification{
NSNumber *reason = [aNotification.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([reason intValue] == MPMovieFinishReasonUserExited) {
// Your done button action here
// [self dismissViewControllerAnimated:YES completion:nil];
NSLog(#"done button tapped");
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerDidExitFullscreenNotification
object:nil];
[self.playerController stop];
[self.playerController.view removeFromSuperview];
}
}
- (IBAction)backButtonTapped:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Helper Methods
- (void)loadVideo:(NSString*)currentPage pagesID:(NSString*)pagesID{
__weak typeof(self) weakSelf = self;
NSString *fbToken = [facebook currentFBAccessToken];
NSString *fbNextVideoURL = [NSString stringWithFormat:#"https://graph.facebook.com/v2.5/%#/videos?access_token=%#&pretty=0&fields=source,description,thumbnails.limit(1),length&limit=10&after=%#", pagesID, fbToken, currentPage];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:fbNextVideoURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *videoDict = [[NSDictionary alloc] initWithDictionary:responseObject];
if (responseObject != nil) {
[weakSelf.videoArray addObjectsFromArray:[videoDict valueForKeyPath:#"data"]];
pageBefore = [videoDict valueForKeyPath:#"paging.cursors.before"];
pageAfter = [videoDict valueForKeyPath:#"paging.cursors.after"];
// Caching pageBefore, pageAfter, thumbnailsURI, titleDescription data to REALM
for (videoInfoToSaveInRealm in weakSelf.videoArray) {
NSDictionary *videoThumbnails = [videoInfoToSaveInRealm valueForKey:#"thumbnails"];
NSArray *thumbnailsData = [videoThumbnails objectForKey:#"data"][0];
[[RLMRealm defaultRealm] transactionWithBlock:^{
[FBVideo createOrUpdateInDefaultRealmWithValue:#{#"id": self.pageID, #"titleDescription": videoInfoToSaveInRealm[#"description"], #"thumbnailsURI": [thumbnailsData valueForKey:#"uri"], #"pageBefore": pageBefore, #"pageAfter": pageAfter}];
}];
[self retrieveDataFromRealm];
}
//NSLog(#"first product's image: %#", (FBVideo *)[FBVideo allObjects]);
// Update UICollectionView UI
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self.collectionView reloadData];
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (void)retrieveDataFromRealm {
RLMResults *objects;
objects = [FBVideo allObjects];
FBVideo *fbVideoRealm = [[FBVideo alloc] init];
for (fbVideoRealm in objects) {
// NSLog(#"realm object count : %d", (int)objects.count);
NSLog(#"realm description : %#", fbVideoRealm.titleDescription);
NSLog(#"realm thumbnails URi : %#", fbVideoRealm.thumbnailsURI);
NSLog(#"realm page before : %#", fbVideoRealm.pageBefore);
NSLog(#"realm page after : %#", fbVideoRealm.pageAfter);
};
}
#end
Thank you in advance.
You should store the Facebook API response directly in Realm (don't display it right away), and then you can follow the pattern demonstrated in Realm's "TableView" example to back your UITableView with an RLMResults, and update the table when its data changes.
Since you'll always be loading data from the Realm this way, you get offline mode "for free".
I'm currently showing a Date Picker of the kind UIDatePickerModeCountDownTimer that uses:
- (UIDatePicker *)datePicker {
if (!_datePicker) {
_datePicker = [[UIDatePicker alloc] init];
_datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
_datePicker.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
}
return _datePicker;
}
- (void)setDuration:(NSTimeInterval)duration {
_duration = duration;
self.datePicker.countDownDuration = _duration;
}
... date picker, and shows (in a label) the time from current date to date chosen in future with:
- (void)update {
if (self.time) {
[self setImage:nil forState:UIControlStateNormal];
NSString *title;
NSTimeInterval timeInterval = [self.time doubleValue];
if (self.ticking) {
NSMutableString *dateFormat = [[NSMutableString alloc] init];
if (timeInterval < 0) {
[dateFormat appendString:#"-"];
}
if (fabsf(timeInterval) > 60 * 60) {
[dateFormat appendString:#"hh:"];
}
[dateFormat appendString:#"mm:ss"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = dateFormat;
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
title = [formatter stringFromDate:date];
if ([self.time integerValue] > 0) {
self.circleView.backgroundColor = [UIColor colorWithRed:0.373 green:0.702 blue:0.522 alpha:1];
} else {
self.circleView.backgroundColor = [UIColor colorWithRed:0.820 green:0.373 blue:0.424 alpha:1];
}
} else {
NSMutableString *text = [[NSMutableString alloc] init];
if (fabsf(timeInterval) < 60) {
// Show seconds
[text appendFormat:#"%.0fs", timeInterval];
} else if (fabsf(timeInterval) < 60 * 60) {
// Show minutes
[text appendFormat:#"%.0fm", floorf(timeInterval / 60)];
} else {
// Show hours
[text appendFormat:#"%.0fh", floorf(timeInterval / 60 / 60)];
}
title = text;
self.circleView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.2];
}
[self setTitle:title forState:UIControlStateNormal];
return;
}
[self setTitle:nil forState:UIControlStateNormal];
[self setImage:[UIImage imageNamed:#"plus"] forState:UIControlStateNormal];
self.circleView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.05];
}
... but I switched the DatePicker to UIDatePickerModeDateAndTime and need to figure out how to update my update method with it.
I need to show month/day in addition to hour/minute/second in the label.
If you want a method like delegate, then this can help you..
Add target to your date picker....
[myDatePicker addTarget:self action:#selector(onPickerValueChanged:) forControlEvents:UIControlEventValueChanged];
Remove target in dealloc. Otherwise if your picker is scrolling and viewController is popped, app will crash.
- (void dealloc
{
[myPicker removeTarget:self action:#selector(onPickerValueChanged:) forControlEvents:UIControlEventValueChanged];
[myPicker release];//FOR NON ARC
[super dealloc];//FOR NON ARC
}
Implement value Change like
- (IBAction)onPickerValueChanged:(id)sender
{
[self update];
}
I am putting a twitter feed in my app and no matter what I have tried to do to get the tweets to display in their entirety, I have not been entirely successful. Most tweets show up fine but it's the really long ones that have given me a headache. I thought it was because I was somehow not getting enough lines in my textLabel, but I noticed that if a user has elongated their tweet by hitting enter multiple times the tweets would show up fine. Which leads me to believe somehow it is truncating after a certain amount of characters. I don't know if I'm doing something wrong or if this is just an issue with twitter. If anyone can see anything in my code that is wrong, or could be changed to fix this, please let me know. Thank you
#import "TwitterFeedTVC.h"
#import "TweetVC.h"
#import <QuartzCore/QuartzCore.h>
#import "GTMNSString+HTML.h"
#define REFRESH_HEADER_HEIGHT 52.0f
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#implementation TwitterFeedTVC
#synthesize textPull, textRelease, textLoading, refreshHeaderView, refreshLabel, refreshArrow, refreshSpinner, twitterFeedName, twitterFeedTitle;
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil)
{
[self setupStrings];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.twitterFeedTitle.text = self.twitterFeedName;
self.navigationItem.title = self.twitterFeedName;
[self fetchTweets];
[self addPullToRefreshHeader];
}
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&screen_name=johnnelm9r&count=100"]];
if (data == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"Twitter Is Not Responding. Please Try Again Later!"
delegate:self
cancelButtonTitle:#"Kali Baby"
otherButtonTitles: nil];
[alert show];
}
else
{
NSError *error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (void)viewDidUnload
{
[super viewDidUnload];
textPull = nil;
textRelease = nil;
textLoading = nil;
refreshHeaderView = nil;
refreshLabel = nil;
refreshArrow = nil;
refreshSpinner = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), CGFLOAT_MAX);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height, 44.0f);
return height + ((CELL_CONTENT_MARGIN * 2) + 9);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"EEE MMM dd HH:mm:ss +0000 yyyy"];
NSDate *currentDate = [dateFormatter dateFromString:[tweet objectForKey:#"created_at"]];
NSDate *todayDate = [NSDate date];
NSString *date = [dateFormatter stringFromDate:currentDate];
double timeInterval = [currentDate timeIntervalSinceDate:todayDate];
timeInterval = timeInterval * -1;
if (timeInterval < 1)
{
date = #"never";
}
else if (timeInterval <60)
{
date = #"less than a minute ago";
}
else if (timeInterval <3600)
{
int diff = round(timeInterval / 60);
date = [NSString stringWithFormat:#"%d minutes ago", diff];
}
else if (timeInterval < 86400)
{
int diff = round(timeInterval / 60 / 60);
date = [NSString stringWithFormat:#"%d hours ago", diff];
}
else if (timeInterval < 2629743)
{
int diff = round(timeInterval / 60 / 60 / 24);
date = [NSString stringWithFormat:#"%d days ago", diff];
}
else
{
date = #"never";
}
cell.textLabel.text = [[tweet objectForKey:#"text"] gtm_stringByUnescapingFromHTML];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", date];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageUrl = [[tweet objectForKey:#"user"] objectForKey:#"profile_image_url"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:data];
[cell addSubview:cell.imageView];
});
});
return cell;
}
- (void)setupStrings
{
textPull = #"Pull Down To Be Fresh...";
textRelease = #"Release To Be Fresh...";
textLoading = #"Getting Loaded...";
}
- (void)addPullToRefreshHeader
{
refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
refreshHeaderView.backgroundColor = [UIColor clearColor];
refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
refreshLabel.backgroundColor = [UIColor clearColor];
refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
refreshLabel.textAlignment = UITextAlignmentCenter;
refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"KrizzOpener.png"]];
refreshArrow.frame = CGRectMake(floorf((REFRESH_HEADER_HEIGHT - 27) / 2),
(floorf(REFRESH_HEADER_HEIGHT - 44) / 2),
27, 44);
refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
refreshSpinner.hidesWhenStopped = YES;
[refreshHeaderView addSubview:refreshLabel];
[refreshHeaderView addSubview:refreshArrow];
[refreshHeaderView addSubview:refreshSpinner];
[self.tableView addSubview:refreshHeaderView];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
if (isLoading) return;
isDragging = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (isLoading) {
if (scrollView.contentOffset.y > 0)
self.tableView.contentInset = UIEdgeInsetsZero;
else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
self.tableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (isDragging && scrollView.contentOffset.y < 0) {
[UIView beginAnimations:nil context:NULL];
if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
refreshLabel.text = self.textRelease;
} else {
refreshLabel.text = self.textPull;
}
[UIView commitAnimations];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (isLoading) return;
isDragging = NO;
if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT)
{
[self startLoading];
}
}
- (void)startLoading {
isLoading = YES;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.tableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
refreshLabel.text = self.textLoading;
refreshArrow.hidden = YES;
[refreshSpinner startAnimating];
[UIView commitAnimations];
[self refresh];
}
- (void)stopLoading {
isLoading = NO;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.3];
[UIView setAnimationDidStopSelector:#selector(stopLoadingComplete:finished:context:)];
self.tableView.contentInset = UIEdgeInsetsZero;
UIEdgeInsets tableContentInset = self.tableView.contentInset;
tableContentInset.top = 0.0;
self.tableView.contentInset = tableContentInset;
[UIView commitAnimations];
}
- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
refreshLabel.text = self.textPull;
refreshArrow.hidden = NO;
[refreshSpinner stopAnimating];
}
- (void)refresh {
[self fetchTweets];
[self performSelector:#selector(stopLoading) withObject:nil afterDelay:2.7];
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"tweetVC"])
{
NSInteger row = [[self tableView].indexPathForSelectedRow row];
NSDictionary *tweet = [tweets objectAtIndex:row];
TweetVC *tweetVC = segue.destinationViewController;
tweetVC.detailItem = tweet;
}
}
After a lot of investigation I found an article somewhere that said there is a difference between the text key and the retweeted_status.text key. The tweets being truncated were, in fact, retweets from the user using the text key. However, the retweeted_status.text key is only the tweet that was retweeted, without the user who originally tweeted it. That sucks because the retweeted_status.text key is NOT truncated. Ahhh, the joys of programming. Hopefully the new twitter API will address this. I hope this answer helps somebody.
Here is the link to what I found in case anyone is interested: http://code.google.com/p/twitter-api/issues/detail?id=2261
I haven't gone through your code, but I thought of mentioning this point that Twitter only allows tweet 140 characters long! This is the basic rule of a tweet. So no matter what you do tweet with mode than 140 characters will be truncated.
I hope this is not the issue?
Am getting confused here.I had implemented a calender control in ios application.But not able to find the position of a particular date when the user selects the date.How to find the position of a particular date which is selected by the user?Please some one help me or give me some advice.Provide any sample codes.Great answers would be appreciated.
In DayButton.h
//
// DayButton.h
// DDCalendarView
//
//
//
#import <UIKit/UIKit.h>
#protocol DayButtonDelegate <NSObject>
- (void)dayButtonPressed:(id)sender;
#end
#interface DayButton : UIButton {
id <DayButtonDelegate> delegate;
NSDate *buttonDate;
}
#property (nonatomic, assign) id <DayButtonDelegate> delegate;
#property (nonatomic, copy) NSDate *buttonDate;
- (id)buttonWithFrame:(CGRect)buttonFrame;
#end
In DayButton.m
//
// DayButton.m
// DDCalendarView
//
//
#import "DayButton.h"
#implementation DayButton
#synthesize delegate, buttonDate;
- (id)buttonWithFrame:(CGRect)buttonFrame {
self = [DayButton buttonWithType:UIButtonTypeCustom];
self.frame = buttonFrame;
self.titleLabel.textAlignment = UITextAlignmentRight;
self.backgroundColor = [UIColor clearColor];
[self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self addTarget:delegate action:#selector(dayButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
UILabel *titleLabel = [self titleLabel];
CGRect labelFrame = titleLabel.frame;
int framePadding = 4;
labelFrame.origin.x = self.bounds.size.width - labelFrame.size.width - framePadding;
labelFrame.origin.y = framePadding;
[self titleLabel].frame = labelFrame;
}
- (void)dealloc {
[super dealloc];
}
#end
In DDCalenderView.h
//
// DDCalendarView.h
// DDCalendarView
//
//
#import <UIKit/UIKit.h>
#import "DayButton.h"
#protocol DDCalendarViewDelegate <NSObject>
- (void)dayButtonPressed:(DayButton *)button;
#optional
- (void)prevButtonPressed;
- (void)nextButtonPressed;
#end
#interface DDCalendarView : UIView <DayButtonDelegate> {
id <DDCalendarViewDelegate> delegate;
NSString *calendarFontName;
UILabel *monthLabel;
NSMutableArray *dayButtons;
NSCalendar *calendar;
float calendarWidth;
float calendarHeight;
float cellWidth;
float cellHeight;
int currentMonth;
int currentYear;
}
#property(nonatomic, assign) id <DDCalendarViewDelegate> delegate;
- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName delegate:(id)theDelegate;
- (void)updateCalendarForMonth:(int)month forYear:(int)year;
- (void)drawDayButtons;
- (void)prevBtnPressed:(id)sender;
- (void)nextBtnPressed:(id)sender;
#end
In DDCalenderView.m
//
// DDCalendarView.m
// DDCalendarView
//
//
#import "DDCalendarView.h"
#implementation DDCalendarView
#synthesize delegate;
- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName delegate:(id)theDelegate {
if ((self = [super initWithFrame:frame])) {
self.delegate = theDelegate;
//Initialise vars
calendarFontName = fontName;
calendarWidth = frame.size.width;
calendarHeight = frame.size.height;
cellWidth = frame.size.width / 7.0f;
cellHeight = frame.size.height / 14.0f;
//View properties
// UIColor *bgPatternImage = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"square-paper.png"]];
//
// self.backgroundColor = bgPatternImage;
// [bgPatternImage release];
//Set up the calendar header
self.backgroundColor=[UIColor whiteColor];
UIButton *prevBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[prevBtn setImage:[UIImage imageNamed:#"left-arrow.png"] forState:UIControlStateNormal];
prevBtn.frame = CGRectMake(0, 0, cellWidth, cellHeight);
[prevBtn addTarget:self action:#selector(prevBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[nextBtn setImage:[UIImage imageNamed:#"right-arrow.png"] forState:UIControlStateNormal];
nextBtn.frame = CGRectMake(calendarWidth - cellWidth, 0, cellWidth, cellHeight);
[nextBtn addTarget:self action:#selector(nextBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
CGRect monthLabelFrame = CGRectMake(cellWidth, 0, calendarWidth - 2*cellWidth, cellHeight);
monthLabel = [[UILabel alloc] initWithFrame:monthLabelFrame];
monthLabel.font = [UIFont fontWithName:calendarFontName size:18];
monthLabel.textAlignment = UITextAlignmentCenter;
monthLabel.backgroundColor = [UIColor clearColor];
monthLabel.textColor = [UIColor blackColor];
//Add the calendar header to view
[self addSubview: prevBtn];
[self addSubview: nextBtn];
[self addSubview: monthLabel];
//Add the day labels to the view
char *days[7] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
for(int i = 0; i < 7; i++) {
CGRect dayLabelFrame = CGRectMake(i*cellWidth, cellHeight, cellWidth, cellHeight);
UILabel *dayLabel = [[UILabel alloc] initWithFrame:dayLabelFrame];
dayLabel.text = [NSString stringWithFormat:#"%s", days[i]];
dayLabel.textAlignment = UITextAlignmentCenter;
dayLabel.backgroundColor = [UIColor clearColor];
dayLabel.font = [UIFont fontWithName:calendarFontName size:16];
dayLabel.textColor = [UIColor darkGrayColor];
[self addSubview:dayLabel];
[dayLabel release];
}
[self drawDayButtons];
//Set the current month and year and update the calendar
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *dateParts = [calendar components:unitFlags fromDate:[NSDate date]];
currentMonth = [dateParts month];
currentYear = [dateParts year];
[self updateCalendarForMonth:currentMonth forYear:currentYear];
}
return self;
}
- (void)drawDayButtons {
dayButtons = [[NSMutableArray alloc] initWithCapacity:42];
for (int i = 0; i < 6; i++) {
for(int j = 0; j < 7; j++) {
CGRect buttonFrame = CGRectMake(j*cellWidth, (i+2)*cellHeight, cellWidth, cellHeight);
DayButton *dayButton = [[DayButton alloc] buttonWithFrame:buttonFrame];
dayButton.titleLabel.font = [UIFont fontWithName:calendarFontName size:14];
dayButton.delegate = self;
[dayButtons addObject:dayButton];
[dayButton release];
[self addSubview:[dayButtons lastObject]];
}
}
}
- (void)updateCalendarForMonth:(int)month forYear:(int)year {
char *months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
monthLabel.text = [NSString stringWithFormat:#"%s %d", months[month - 1], year];
//Get the first day of the month
NSDateComponents *dateParts = [[NSDateComponents alloc] init];
[dateParts setMonth:month];
[dateParts setYear:year];
[dateParts setDay:1];
NSDate *dateOnFirst = [calendar dateFromComponents:dateParts];
[dateParts release];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:dateOnFirst];
int weekdayOfFirst = [weekdayComponents weekday];
//Map first day of month to a week starting on Monday
//as the weekday component defaults to 1->Sun, 2->Mon...
if(weekdayOfFirst == 1) {
weekdayOfFirst = 7;
} else {
--weekdayOfFirst;
}
int numDaysInMonth = [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:dateOnFirst].length;
int day = 1;
for (int i = 0; i < 6; i++) {
for(int j = 0; j < 7; j++) {
int buttonNumber = i * 7 + j;
DayButton *button = [dayButtons objectAtIndex:buttonNumber];
button.enabled = NO; //Disable buttons by default
[button setTitle:nil forState:UIControlStateNormal]; //Set title label text to nil by default
[button setButtonDate:nil];
if(buttonNumber >= (weekdayOfFirst - 1) && day <= numDaysInMonth) {
[button setTitle:[NSString stringWithFormat:#"%d", day]
forState:UIControlStateNormal];
NSDateComponents *dateParts = [[NSDateComponents alloc] init];
[dateParts setMonth:month];
[dateParts setYear:year];
[dateParts setDay:day];
NSDate *buttonDate = [calendar dateFromComponents:dateParts];
[dateParts release];
[button setButtonDate:buttonDate];
button.enabled = YES;
++day;
}
}
}
}
- (void)prevBtnPressed:(id)sender {
if(currentMonth == 1) {
currentMonth = 12;
--currentYear;
} else {
--currentMonth;
}
[self updateCalendarForMonth:currentMonth forYear:currentYear];
if ([self.delegate respondsToSelector:#selector(prevButtonPressed)]) {
[self.delegate prevButtonPressed];
}
}
- (void)nextBtnPressed:(id)sender {
if(currentMonth == 12) {
currentMonth = 1;
++currentYear;
} else {
++currentMonth;
}
[self updateCalendarForMonth:currentMonth forYear:currentYear];
if ([self.delegate respondsToSelector:#selector(nextButtonPressed)]) {
[self.delegate nextButtonPressed];
}
}
- (void)dayButtonPressed:(id)sender {
DayButton *dayButton = (DayButton *) sender;
[self.delegate dayButtonPressed:dayButton];
}
- (void)dealloc {
[calendar release];
[dayButtons release];
[super dealloc];
}
#end
In MainViewController.h
//
// MainViewController.h
// DDCalendarView
//
//
#import <UIKit/UIKit.h>
#import "DDCalendarView.h"
#interface MainViewController : UIViewController <DDCalendarViewDelegate> {
DDCalendarView *calendarView;
}
#end
In MainVIewController.m
//
// MainViewController.m
// DDCalendarView
//
//
#import "MainViewController.h"
#implementation MainViewController
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
UIView *appView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
calendarView = [[DDCalendarView alloc] initWithFrame:appView.bounds fontName:#"AmericanTypewriter" delegate:self];
self.view = appView;
[appView release];
[self.view addSubview: calendarView];
}
- (void)dayButtonPressed:(DayButton *)button {
//For the sake of example, we obtain the date from the button object
//and display the string in an alert view
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *theDate = [dateFormatter stringFromDate:button.buttonDate];
[dateFormatter release];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *theDate = [dateFormatter stringFromDate:button.buttonDate];
[dateFormatter release];
// UIAlertView *dateAlert = [[UIAlertView alloc]
// initWithTitle:#"Date Pressed"
// message:theDate
// delegate:self
// cancelButtonTitle:#"Ok"
// otherButtonTitles:nil];
// [dateAlert show];
// [dateAlert release];
//
timeEntry *time=[[timeEntry alloc]init];
[time setDate:theDate];
[self.navigationController pushViewController:time animated:YES];
[time release];
}
- (void)nextButtonPressed {
NSLog(#"Next...");
}
- (void)prevButtonPressed {
NSLog(#"Prev...");
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
I took an image above the calender.If the user selects the date,the image has to move to that date in horizontal or vertical position.Is Animation necessary?If yes,how to handle or otherwise can anyone help in their own manner.Please.Great answers would be appreciated.
Have you ever tried Tapku library?
Its preferable for custom calender controls. Hope this helps you.
I would recommend using Kal. I use it for a month view and it works great. It keeps track of the date even when you move to another view.
EDIT:
get the location of the tap check out this link