change UILocalnotification code o UNUserNotification - objective-c

I want to change the below code to UNUserNotification format.I can"t change it into the correct format. Can any one help me?
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
bool neverRepeats = true;
for(id key in _repeatDays) {
if([[_repeatDays objectForKey:key] boolValue]) {
neverRepeats = false;
localNotification.fireDate = _alarmTime;
localNotification.alertBody = #"Title";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.alertAction = #"I'm up, I'm up!";
localNotification.repeatInterval = NSWeekCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}
if(neverRepeats) {
if([_alarmTime earlierDate:today] == today) {
localNotification.fireDate = _alarmTime;
localNotification.alertBody = #"Title";
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.alertAction = #"I'm up, I'm up!";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}

Related

Array is deleting the last object in Xcode

Here is my main view controller. I am populating a custom calendar with events from an xml file. This is working fine... Im also adding my own events. I use the same array for both. It appears that when I add a new event to the array. It deletes the previous one.
#import "CalendarViewController.h"
#import "HeaderCollectionReusableView.h"
#import "CalendarCollectionViewCell.h"
#import "EventViewController.h"
#import "AppDelegate.h"
#import "events.h"
#import "AddViewController.h"
#interface CalendarViewController ()
#end
#implementation CalendarViewController
UIImageView *navBarHairlineImageView;
BOOL _viewDidLayoutSubviewsForTheFirstTime = YES;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"VIEW DID LOAD");
// Do any additional setup after loading the view.
self.title = #"Calendar";
//\n in xml is encoded as
_viewDidLayoutSubviewsForTheFirstTime = YES;
if (!_calendar) {
[self setCalendar:[NSCalendar currentCalendar]];
}
_date = [[NSDate alloc] init];
NSDateComponents *components = [_calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:_date];
// set calendar from 2000 to current year + 10 years range
long year = components.year;
long month = components.month;
long day = components.day;
// NSLog(#"%ld %ld %ld", day, month, year);
_initialSection = (year - 2000) * 12 + month - 1; // index sections start at 0
components.day = 1;
components.month = 1;
components.year = 2000;
_firstDate = [_calendar dateFromComponents:components];
components.year = year + 10;
components.day = -1;
_lastDate = [_calendar dateFromComponents:components];
UINavigationBar *navigationBar = self.navigationController.navigationBar;
navBarHairlineImageView = [self findHairlineImageViewUnder:navigationBar];
UIView *bottomBorder = [[UIView alloc] init];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, _days.frame.size.height - 0.5, _days.frame.size.width, 0.5);
[_days addSubview:bottomBorder];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSData *data = appDelegate.data;
NSString *a = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *b = [a stringByReplacingOccurrencesOfString:#"
" withString:#"\n"];
data = [b dataUsingEncoding:NSUTF8StringEncoding];
//NSLog(#"%#", b);
_eventParser = [[NSXMLParser alloc] initWithData:data];
_eventsA = [[NSMutableArray alloc] init];
[_eventParser setDelegate:self];
[_eventParser parse];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
_databasesPath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"ev.db"]];
// NSFileManager *filemgr = [NSFileManager defaultManager];
const char *dbpaths = [_databasesPath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpaths, &_myDB) == SQLITE_OK){
NSString *querySQL = #"SELECT * FROM event";
const char *query_stmt = [querySQL UTF8String];
NSLog(#"I SEE YOUFIRST");
if(sqlite3_prepare_v2(_myDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
// const char *query_stmt = [querySQL UTF8String];
//query_stmt = [querySQL UTF8String];
// NSMutableArray *allMessages = [[NSMutableArray alloc] init];
NSLog(#"I SEE YOU");
if(sqlite3_prepare_v2(_myDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
while(sqlite3_step(statement) == SQLITE_ROW){
NSString *typeField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 0)];
NSString *descriptionField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 1)];
NSString *dateField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 2)];
// NSLog(#"%#", dateField);
// NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: typeField, #"typeField", descriptionField, #"descriptionField", dateField, #"dateField", nil];
// [allMessages addObject:dict];
_currentevent.eventType = typeField; //[dict objectForKey:#"typeField"];
_currentevent.eventDate = dateField; //[dict objectForKey:#"dateField"];
_currentevent.eventDescription = descriptionField; //[dict objectForKey:#"descriptionField"];
if (![_eventsA containsObject:_currentevent]){
[self.eventsA addObject:_currentevent];
}
// NSLog(#"Type: %# Description:%# Date:%#" , typeField, descriptionField, dateField );
//[_eventsA addObject:dateField];
// [_eventsA addObject:nameField];
//[_eventsA addObject:typeField];
}
sqlite3_finalize(statement);
}
sqlite3_close(_myDB);
}
}
else {
NSLog (#"Failed to add event");
}
NSLog(#"%lu" , (unsigned long)[_eventsA count]);
for(int i = 0; i < [_eventsA count]; i++) {
events *ex = [_eventsA objectAtIndex:i];
NSString *ds = ex.eventDate;
NSString *dd = ex.eventDescription;
NSLog(#"%# %#", ds, dd);
}
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Only scroll when the view is rendered for the first time
if (_viewDidLayoutSubviewsForTheFirstTime) {
_viewDidLayoutSubviewsForTheFirstTime = NO;
UICollectionViewLayoutAttributes *attributes = [_calendarCollectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_initialSection]];
CGRect rect = attributes.frame;
[_calendarCollectionView setContentOffset:CGPointMake(_calendarCollectionView.frame.origin.x, rect.origin.y - 32) animated:NO];
}
}
// find and remove hairline image under top bar
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
-(void)viewWillAppear:(BOOL)animated {
navBarHairlineImageView.hidden = YES;
[self viewDidLoad];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
navBarHairlineImageView.hidden = NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//#pragma mark -
#pragma mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
return [_calendar components:NSCalendarUnitMonth fromDate:_firstDate toDate:_lastDate options:0].month + 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
NSDate *firstOfMonth = [self firstOfMonthForSection:section];
NSRange rangeOfWeeks = [_calendar rangeOfUnit:NSCalendarUnitWeekOfMonth inUnit:NSCalendarUnitMonth forDate:firstOfMonth];
//We need the number of calendar weeks for the full months (it will maybe include previous month and next months cells)
int daysPerWeek = 7;
return (rangeOfWeeks.length * daysPerWeek);
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"calendarCell" forIndexPath:indexPath];
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
NSDateComponents *cellDateComponents = [_calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:cellDate];
NSDateComponents *firstOfMonthsComponents = [_calendar components:NSCalendarUnitMonth fromDate:firstOfMonth];
NSDateComponents *todayComponents = [_calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
if(cellDateComponents.month == firstOfMonthsComponents.month) {
NSString *day = #"";
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"d";
day = [dateFormatter stringFromDate:cellDate];
cell.dateNumber.text = day;
cell.dateNumber.layer.cornerRadius = 7.0;
cell.dateNumber.clipsToBounds = YES;
if(cellDateComponents.day == todayComponents.day &&
cellDateComponents.month == todayComponents.month &&
cellDateComponents.year == todayComponents.year) {
cell.dateNumber.backgroundColor = [UIColor redColor];
cell.dateNumber.textColor = [UIColor whiteColor];
}
else {
cell.dateNumber.backgroundColor = [UIColor clearColor];
cell.dateNumber.textColor = [UIColor blackColor];
if(indexPath.row % 7 == 0 || (indexPath.row + 1) % 7 == 0)
cell.dateNumber.textColor = [UIColor lightGrayColor];
else
cell.dateNumber.textColor = [UIColor blackColor];
}
cell.event.layer.cornerRadius = 3.0;
cell.event.clipsToBounds = YES;
NSDateFormatter *eventFormatter = [[NSDateFormatter alloc] init];
eventFormatter.dateFormat = #"yyyy-MM-dd";
NSString *dateCell = [eventFormatter stringFromDate:cellDate];
NSString *markedEvent = #"";
for(int i = 0; i < [_eventsA count]; i++) {
events *temp = [_eventsA objectAtIndex:i];
markedEvent = temp.eventDate;
if([markedEvent isEqualToString:dateCell]) {
cell.event.backgroundColor = [UIColor lightGrayColor];
cell.hasEvent = YES;
}
}
}
else {
cell.dateNumber.text = #"";
}
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
#pragma mark - UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
//We don't want to select Dates that are "disabled"
if (![self isEnabledDate:cellDate]) {
return NO;
}
NSDateComponents *cellDateComponents = [_calendar components:NSCalendarUnitDay|NSCalendarUnitMonth fromDate:cellDate];
NSDateComponents *firstOfMonthsComponents = [_calendar components:NSCalendarUnitMonth fromDate:firstOfMonth];
return (cellDateComponents.month == firstOfMonthsComponents.month);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.dateNumber.layer.cornerRadius = 7.0;
cell.dateNumber.clipsToBounds = YES;
cell.dateNumber.backgroundColor = [UIColor grayColor];
cell.dateNumber.textColor = [UIColor whiteColor];
_selectedDate = [self dateForCellAtIndexPath:indexPath];
if(cell.hasEvent) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"EEEE MMMM d, yyyy";
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
NSString *stringDate = [formatter stringFromDate:cellDate];
NSString *stringType;
NSString *stringDescription;
NSString *tempDate;
NSDateFormatter *fm = [[NSDateFormatter alloc] init];
fm.dateFormat = #"yyyy-MM-dd";
NSString *cd = [fm stringFromDate:cellDate];
for(int i = 0; i <[_eventsA count]; i++){
events *temp1 = [_eventsA objectAtIndex:i];
tempDate = temp1.eventDate;
//NSLog(#"%#", tempDate);
// NSLog(#"%#", stringDate);
// NSLog(#"%#", cd);
if([cd isEqualToString:tempDate]){
//NSLog(#"%#", tempDate);
stringType= temp1.eventType;
stringDescription = temp1.eventDescription;
}
else{
}
}
EventViewController *events = [self.storyboard instantiateViewControllerWithIdentifier:#"eventController"];
events.stringDate = stringDate;
events.stringType = stringType;
events.stringDescription = stringDescription;
[self.navigationController pushViewController:events animated:YES];
}
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell =(CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
if([self isTodayDate:cellDate]) {
cell.dateNumber.backgroundColor = [UIColor redColor];
cell.dateNumber.textColor = [UIColor whiteColor];
}
else {
cell.dateNumber.backgroundColor = [UIColor clearColor];
cell.dateNumber.textColor = [UIColor blackColor];
}
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader) {
HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"calendarHeader" forIndexPath:indexPath];
UIFont *font = [UIFont fontWithName:#"HelveticaNeue-Light" size:12];
headerView.month.font = font;
headerView.month.textColor = [UIColor redColor];
UIView *bottomBorder = [UIView new];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, headerView.frame.size.height - 1, headerView.frame.size.width, 1);
[headerView addSubview:bottomBorder];
NSDateFormatter *headerDateFormatter = [[NSDateFormatter alloc] init];
headerDateFormatter.calendar = _calendar;
headerDateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:#"yyyy LLLL" options:0 locale:_calendar.locale];
NSString *headerTitle = [headerDateFormatter stringFromDate:[self firstOfMonthForSection:indexPath.section]].uppercaseString;
headerView.month.text = headerTitle;
reusableview = headerView;
}
return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGFloat width = self.view.frame.size.width / 7.0;
CGFloat height = width;
return CGSizeMake(width, height);
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
UICollectionViewFlowLayout *flowLayout = (id)self.calendarCollectionView.collectionViewLayout;
[flowLayout invalidateLayout]; //force the elements to get laid out again with the new size
}
// Calendar methods
- (NSDate *)firstOfMonthForSection:(NSInteger)section
{
NSDateComponents *offset = [NSDateComponents new];
offset.month = section;
return [_calendar dateByAddingComponents:offset toDate:_firstDate options:0];
}
- (NSDate *)dateForCellAtIndexPath:(NSIndexPath *)indexPath
{
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSInteger ordinalityOfFirstDay = [_calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:firstOfMonth];
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = (1 - ordinalityOfFirstDay) + indexPath.item;
return [_calendar dateByAddingComponents:dateComponents toDate:firstOfMonth options:0];
}
- (BOOL)isEnabledDate:(NSDate *)date
{
NSDate *clampedDate = [self clampDate:date toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
if (([clampedDate compare:_firstDate] == NSOrderedAscending) || ([clampedDate compare:_lastDate] == NSOrderedDescending)) {
return NO;
}
return YES;
}
- (NSDate *)clampDate:(NSDate *)date toComponents:(NSUInteger)unitFlags
{
NSDateComponents *components = [_calendar components:unitFlags fromDate:date];
return [_calendar dateFromComponents:components];
}
- (BOOL)isTodayDate:(NSDate *)date
{
return [self clampAndCompareDate:date withReferenceDate:[NSDate date]];
}
- (BOOL)isSelectedDate:(NSDate *)date
{
if (!_selectedDate) {
return NO;
}
return [self clampAndCompareDate:date withReferenceDate:_selectedDate];
}
- (BOOL)clampAndCompareDate:(NSDate *)date withReferenceDate:(NSDate *)referenceDate
{
NSDate *refDate = [self clampDate:referenceDate toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
NSDate *clampedDate = [self clampDate:date toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
return [refDate isEqualToDate:clampedDate];
}
#pragma mark - NSXMLParser Delegate
- (void) parserDidStartDocument:(NSXMLParser *)parser {
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"event"])
_currentevent = [[events alloc] init];
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
_currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"type"]) {
_currentevent.eventType = _currentNodeContent;
}
if([elementName isEqualToString:#"date"]) {
_currentevent.eventDate = _currentNodeContent;
}
if([elementName isEqualToString:#"description"]) {
_currentevent.eventDescription = _currentNodeContent;
}
if([elementName isEqualToString:#"event"]) {
[_eventsA addObject:_currentevent];
}
}
- (void) parserDidEndDocument:(NSXMLParser *)parser {
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if ([segue.identifier isEqualToString:#"segueAdd"]) {
AddViewController *modalVC = (AddViewController *)segue.destinationViewController;
// modalVC.cVC = self;
modalVC.sDate = _selectedDate;
}
}
- (IBAction)todayButton:(id)sender {
UICollectionViewLayoutAttributes *attributes = [_calendarCollectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_initialSection]];
CGRect rect = attributes.frame;
[_calendarCollectionView setContentOffset:CGPointMake(_calendarCollectionView.frame.origin.x, rect.origin.y - 32) animated:YES];
}
- (IBAction)addButton:(id)sender {
[self performSegueWithIdentifier:#"segueAdd" sender:self];
}
#end
This is my view controller where I'm adding events to sqlite
#import "AddViewController.h"
#import "CalendarViewController.h"
#interface AddViewController ()
#end
#implementation AddViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"This is the Date:%#", _sDate);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"ev.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO) {
const char *dbpath = [_databasePath UTF8String];
_status.text = #"No TABLE";
if (sqlite3_open(dbpath, &_evDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS EVENT (TYPE TEXT, DESCRIPTION TEXT, DATE VARCHAR(255))";
if (sqlite3_exec(_evDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
_status.text = #"Failed to create table";
}
sqlite3_close(_evDB);
} else {
_status.text = #"Failed to open/create database";
}
}
// Do any additional setup after loading the view.
// [CalendarViewController.view.eventsA addObject:_currentevent];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {
UITouch *touch = [[event allTouches] anyObject];
if ([_etype isFirstResponder] && (_etype != touch.view)) {
// _inputText lost focus - close keyboard
[_etype resignFirstResponder];
}
if ([_edescription isFirstResponder] && (_edescription != touch.view)) {
// _inputText lost focus - close keyboard
[_edescription resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if ([segue.identifier isEqualToString:#"goBack"]) {
CalendarViewController *destViewController = (CalendarViewController *)segue.destinationViewController;
destViewController.myDB = _evDB;
destViewController.databasesPath = _databasePath;
destViewController.eventDate = _cd;
destViewController.eventType = _type1;
destViewController.eventDescription = _d1;
destViewController.eventsA = _mArray;
}
}
- (IBAction)addEvent:(id)sender {
// NSMutableArray *temporaryArray = [NSMutableArray arrayWithObject:_sDate];
//= [NSMutableArray arrayWithObject:selectedRow];
// NSLog(#"%#", _sDate);
//NSLog(#"%#", type);
//NSLog(#"%#", description);
//_cVC.eventsA = temporaryArray;
_type1 = [[NSString alloc]initWithString:[_etype text]];
_d1 = [[NSString alloc]initWithString:[_edescription text]];
// NSLog(#"%#", type1);
//NSLog(#"%#", description);
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
NSDateFormatter *fm = [[NSDateFormatter alloc] init];
fm.dateFormat = #"yyyy-MM-dd";
_cd = [fm stringFromDate:_sDate];
NSLog(#"%#" , _cd);
// save
if (sqlite3_open(dbpath, &_evDB) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO EVENT VALUES (\"%#\", \"%#\", \"%#\")", _type1, _d1, _cd];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_evDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
_status.text = #"Event added";
_etype.text = #"";
_edescription.text = #"";
// UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
/*CalendarViewController *destViewController = [storyboard instantiateViewControllerWithIdentifier:#"ViewController"];
destViewController.myDB = _myDB;
destViewController.databasesPath = _databasePath;
destViewController.eventDate = cd;
destViewController.eventType = type1;
destViewController.eventDescription = description;
*/
// super.navigationController.viewDidLoad;
[self.navigationController popToRootViewControllerAnimated:YES];
//[self performSegueWithIdentifier:#"goBack" sender:self];
// CalendarViewController *cal = [self.storyboard instantiateViewControllerWithIdentifier:#"ViewController"];
//[self.navigationController pushViewController:cal animated:YES];
// _cevent.eventType =_type1;
//_cevent.eventDate = _cd;
//_cevent.eventDescription = _d1;
//[_mArray addObject:_cevent];
} else {
_status.text = #"Failed to add event";
}
sqlite3_finalize(statement);
sqlite3_close(_evDB);
}
}
#end
if (![_eventsA containsObject:_currentevent]) {
[self.eventsA addObject:_currentevent];
Problem 1. After one [self.eventsA addObject:_currentevent], [_eventsA containsObject:_currentevent] will return YES.
Problem 2. NSMutableArray stores pointers to objects and doesn't copy an object when it is added. If you add _currentevent to self.eventsA and then change the properties of _currentevent, the properties of the added _currentevent will change. If you remove if (![_eventsA containsObject:_currentevent]) and keep adding the same object, which is possible, all elements of _eventsA will have the properties of the last _currentevent.
Solution: create a new local event object in each iteration of the while loop.

Action buttons on Remote Notification iOS 10 (objective C) is not coming IIViewDeckController

After lot of googling and following apple's doc , still I am not able to get action button in remote(push) notification but I am getting it in local notification by following the same code for local notification.
- (void)triggerAndRegisterNotification {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
// create actions
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// create actions
UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:#"com.AG.yes"
title:#"Save"
options:UNNotificationActionOptionForeground];
UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:#"com.AG.no"
title:#"Decline"
options:UNNotificationActionOptionDestructive];
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"com.AG.snooze"
title:#"Snooze"
options:UNNotificationActionOptionDestructive];
NSArray *notificationActions = #[ acceptAction, declineAction, snoozeAction ];
// create a category
UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier actions:notificationActions intentIdentifiers:#[] options:UNNotificationCategoryOptionNone];
NSSet *categories = [NSSet setWithObject:inviteCategory];
// registration
[center setNotificationCategories:categories];
#endif
} else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0")) {
// create actions
UIMutableUserNotificationAction *acceptAction =
[[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = #"com.AG.yes";
acceptAction.title = #"Accept";
acceptAction.activationMode =
UIUserNotificationActivationModeBackground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO; //If YES requies
passcode, but does not unlock the device
UIMutableUserNotificationAction *declineAction =
[[UIMutableUserNotificationAction alloc] init];
declineAction.identifier = #"com.AG.no";
acceptAction.title = #"Decline";
acceptAction.activationMode =
UIUserNotificationActivationModeBackground;
declineAction.destructive = YES;
acceptAction.authenticationRequired = NO;
UIMutableUserNotificationAction *snoozeAction =
[[UIMutableUserNotificationAction alloc] init];
snoozeAction.identifier = #"com.AG.snooze";
acceptAction.title = #"Snooze";
snoozeAction.activationMode =
UIUserNotificationActivationModeBackground;
snoozeAction.destructive = YES;
snoozeAction.authenticationRequired = NO;
// create a category
UIMutableUserNotificationCategory *inviteCategory =
[[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = CYLInviteCategoryIdentifier;
NSArray *notificationActions = #[ acceptAction, declineAction,
snoozeAction ];
[inviteCategory setActions:notificationActions
forContext:UIUserNotificationActionContextDefault];
[inviteCategory setActions:notificationActions
forContext:UIUserNotificationActionContextMinimal];
// registration
NSSet *categories = [NSSet setWithObject:inviteCategory];
UIUserNotificationType types = UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication]
registerUserNotificationSettings:settings];
}
/// 2. request authorization for localNotification
[self registerNotificationSettingsCompletionHandler:^(BOOL
granted,
NSError * _Nullable error) {
if (granted) {
NSLog(#"request authorization succeeded!");
[[UIApplication sharedApplication]
registerForRemoteNotifications];
}
}];
**COMMENTED CODE FOR LOCAL NOTIFICATION**
// if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
// #if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
// Deliver the notification at 08:30 everyday
// NSDateComponents *dateComponents = [[NSDateComponents
alloc] init];
// dateComponents.hour = 8;
// dateComponents.minute = 30;
// UNCalendarNotificationTrigger *trigger =
// [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:dateComponents
repeats:YES];
// UNMutableNotificationContent *content =
[[UNMutableNotificationContent alloc] init];
// content.title = [NSString
localizedUserNotificationStringForKey:#"AG said:"
arguments:nil];
// content.body = [NSString
localizedUserNotificationStringForKey:#"Hello Tom!Get up,
let's play with Jerry!" arguments:nil];
// content.sound = [UNNotificationSound
defaultSound];
// content.categoryIdentifier =
CYLInviteCategoryIdentifier;
/// 4. update application icon badge number
// content.badge = #([[UIApplication sharedApplication]
applicationIconBadgeNumber] + 1);
// content.launchImageName = #"any string is ok,such as
微博#iOS程序犭袁";
// Deliver the notification in five seconds.
//*** Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'time interval
must be at least 60 if repeating'
// UNTimeIntervalNotificationTrigger *trigger =
[UNTimeIntervalNotificationTrigger
// triggerWithTimeInterval:60.0f repeats:YES];
// UNNotificationRequest *request = [
UNNotificationRequest
requestWithIdentifier:#"FiveSecond"
// content:content trigger:trigger];
// UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
/// 3. schedule localNotification,The delegate must be set before
the application returns from
applicationDidFinishLaunching:.
// center.delegate = self;
// [center addNotificationRequest:request
withCompletionHandler:^(NSError * _Nullable error) {
// if (!error) {
// NSLog(#"add NotificationRequest succeeded!");
// }
// }];
//#endif
// } else {
/// 3. schedule localNotification
// UILocalNotification *localNotification =
[[UILocalNotification alloc] init];
// localNotification.fireDate = [NSDate
dateWithTimeIntervalSinceNow:5.f];
// localNotification.alertTitle = #"AG said:";
// localNotification.alertBody = #"Hello Tom!Get up,
let's play with Jerry!";
// localNotification.alertAction = #"play with Jerry";
//Identifies the image used as the launch image when the user
taps (or slides) the action button (or slider).
// localNotification.alertLaunchImage =
#"LaunchImage.png";
// localNotification.userInfo = #{ #"CategoryIdentifier"
: CYLInviteCategoryIdentifier };
//
// localNotification.timeZone = [NSTimeZone
defaultTimeZone];
//repeat evey minute, 0 means don't repeat
// localNotification.repeatInterval = NSCalendarUnitMinute;
/// 4. update application icon badge number
// localNotification.applicationIconBadgeNumber =
[[UIApplication sharedApplication]
applicationIconBadgeNumber] + 1;
// [[UIApplication sharedApplication]
scheduleLocalNotification:localNotification];
//
// }
}
/// 3. THIS IS THE METHOD TO AUTHORIZE THE NOTIFICATION
- (void)registerNotificationSettingsCompletionHandler:(void (^)(BOOL
granted, NSError *__nullable error))completionHandler; {
/// 2. request authorization for localNotification
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
[center requestAuthorizationWithOptions:
(UNAuthorizationOptionBadge | UNAuthorizationOptionSound
| UNAuthorizationOptionAlert)
completionHandler:completionHandler];
#endif
} else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0"))
{
// UIUserNotificationSettings
*userNotificationSettings = [UIUserNotificationSettings
settingsForTypes:(UIUserNotificationTypeAlert |
UIUserNotificationTypeSound |
UIUserNotificationTypeBadge)
//
categories:nil];
// UIApplication *application = [UIApplication
sharedApplication];
// [application
registerUserNotificationSettings:userNotificationSettings];
//FIXME:
// !completionHandler ?: completionHandler(granted, error);
}
}
**AND IN** APPDELEGATE.m
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
/// schedule localNotification, the delegate must be set before
// the application returns fromapplicationDidFinishLaunching:.
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
center.delegate = self;
#endif
}
[self triggerAndRegisterNotification];
}
I am using iphone 7 for testing purpose.
Please help me solve this. Thanks in Advance
Payload JSon
aps = {
alert = {
"artist_id" = 16912;
body = "Kurt Rosenwinkel is playing at Joe Henderson Lab at
SFJAZZ Center";
eventid = 149687805;
sound = default;
timestamp = "810b6035-e4d7-4722-81db-7455e81a48fe";
title = "Kurt Rosenwinkel";
tracks = "itunes,spotify";
type = 2;
};
category = "com.wcities.notification";
};
I checked the category identifier which I set in my app is also same as in payload json.
UPDATE
As I debugged and come to the point that from above code I am getting push notification with action buttons but in some where after did finish launching I am changing my windows root view controller to view controller which is a child of IIViewDeckController.
After commenting this line push notification is coming with action buttons. I am totally confused why it is happening because as per my knowledge there should not be any impact on push notifications if I set or present or push any viewcontroller.
please let me know If I am doing any mistakes here. I have shared all code and scenario above.
Thanks
As I am using dockview library so the viewcontrollers which are added in dock view controller had some code related to setting categories as nil.That is the reason due to which I couldn't able to get the action button in remote notification so I remove this extra code and everything is working fine. I am still finding that stupid person who wrote this code. Appretiate the help
in ios 10 notification work with -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
//code
completionHandler(UNNotificationPresentationOptionAlert);
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
}

UIAlertView button is disabled even after picking date from UIDatePicker

The problem is that after picking date from UIDatePicker the "Ok" button of UIAlertView is disabled.I tried ,but no luck.
-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
should be called whenever we type anything in textfield,but when date is entered it's not getting called,but if i type anything from keyboard,its ok then.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0 && indexPath.row == 1)
{
alertView1 = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
alertView1.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
alertView1.tag=1;
alertText = [alertView1 textFieldAtIndex:0];
itemText = [alertView1 textFieldAtIndex:1];
alertText.inputView=datePicker;
itemText.inputView=secondPicker;
[datePicker addTarget:self action:#selector(firstTF) forControlEvents:UIControlEventValueChanged];
[secondPicker addTarget:self action:#selector(secondTF) forControlEvents:UIControlEventValueChanged];
[alertText setPlaceholder:#"From Date"];
[itemText setPlaceholder:#"To Date"];
itemText.secureTextEntry = NO;
[alertView1 show];
}
- (void)firstTF
{
NSDate *date = datePicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
alertText.text = [dateFormat stringFromDate:date];
}
- (void)secondTF
{
NSDate *date = secondPicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateStyle:NSDateFormatterMediumStyle];
itemText.text = [dateFormat stringFromDate:date];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] > 0)
{
NSLog(#"alertViewShouldEnableFirstOtherButton: was called!");
return YES;
}
else
{
return NO;
}
}
This happens because of "alertViewShouldEnableFirstOtherButton" called before you enter the text in to text field. As per your condition in side the method "Done" button will be disable. Remove this method and you will achieve your target.

How to remove the UILocalNotification repeat interval?

i added a UILocalNotification with repeat interval of a minute.
how to remove it?
[[UIApplication sharedApplication] cancelAllLocalNotifications];
just copy it under the method didLaunchWithOptions or viewDidLoad or even on your next UILocalNotification code.
- (BOOL)scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
localNotification.soundName = soundfileName != nil ? soundfileName : UILocalNotificationDefaultSoundName;
localNotification.alertLaunchImage = launchImage;
localNotification.userInfo = userInfo;
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.fireDate timeIntervalSinceDate:localNotification.fireDate] == 0 &&
[notification.alertBody isEqualToString:localNotification.alertBody]
) {
return NO;
}
}
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
return YES;
}
- (NSArray *)allLocalNotifications
{
return [[UIApplication sharedApplication] scheduledLocalNotifications];
}
- (void)cancelLocalNotification:(UILocalNotification *)notification
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
- (void)cancelAllLocalNotifications
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
you should make a unique identifier to remove notification, such as alertBody..
then
- (void)cancelLocalNotificationByAlertBody:(NSString *)alertBody
{
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.alertBody isEqual:alertBodyString] ) {
[self cancelLocalNotification:notification];
break;
}
}
}
Try with
notification.repeatInterval = NSCalendarUnit(rawValue: 0)
This code is in Swift. Try with the same thing in objective-c.

Game Center not showing in iOS 5

I used this tutorial to access GameCenter.
http://www.raywenderlich.com/3276/how-to-make-a-simple-multiplayer-game-with-game-center-tutorial-part-12
I am able to lo in the game center but then if I want to use this code:
SFAppDelegate * delegate = (SFAppDelegate *) [UIApplication sharedApplication].delegate;
[[GCHelper sharedInstance] findMatchWithMinPlayers:2 maxPlayers:2 viewController:self delegate:self];
This code should work, but if I call i it only shows black screen with blue toolbar in above.
the "self" in here is UIViewController and this controller implements the GCHelper delegate methods.
the method find ... looks like this:
- (void)findMatchWithMinPlayers:(int)minPlayers maxPlayers:(int)maxPlayers viewController:(UIViewController *)viewController delegate:(id<GCHelperDelegate>)theDelegate {
if (!gameCenterAvailable) return;
matchStarted = NO;
self.match = nil;
self.presentingViewController = viewController; // ?
delegate = theDelegate;
[presentingViewController dismissModalViewControllerAnimated:NO];
if (pendingInvite != nil)
{
[presentingViewController dismissModalViewControllerAnimated:NO];
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithInvite:pendingInvite] autorelease];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
self.pendingInvite = nil;
self.pendingPlayersToInvite = nil;
}
else
{
[presentingViewController dismissModalViewControllerAnimated:NO];
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = minPlayers;
request.maxPlayers = maxPlayers;
request.playersToInvite = pendingPlayersToInvite;
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
self.pendingInvite = nil;
self.pendingPlayersToInvite = nil;
}
}
I don't know what am I doing wrong....
Thanks for any suggestions for correction.
:)