Add calendar on iCloud on iOS - iphone

i'm trying to add a calendar to the iCloud EKSource, i'm trying to find the iCloud calendar in this way:
EKSource *theSource = nil;
for (EKSource *source in eventStore.sources) {
if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:#"iCloud"]) {
theSource = source;
break;
}
}
but don't find my any EKSource, how i can add a calendar on icloud and see how many calendar are in icloud?

Perhaps something like this will help you..
- (void)saveEventToiCloud {
EKEventStore *eventDB = [[EKEventStore alloc] init];
NSArray *calender = [[eventDB calendars] retain];
NSString * typeString = #"";
EKCalendar *iCloud;
for (EKCalendar *thisCalendar in calenders)
{
EKCalendarType type = thisCalendar.type;
if (type == EKCalendarTypeCalDAV)
{
NSString *calName=[NSString stringWithFormat:#"%#", thisCalendar.title];
NSRange range = [calName rangeOfString:#"iCloud"]; //Couldn't find better way, if there is, then tell me too. :)
if(range.length!=0)
{
//icloud
iCloud = thisCalendar;
break;
}
else
{
//any other email account
}
}
}
if(iCloud){
NSError *error = nil;
EKEvent *thisEvent = [[EKEvent eventWithEventStore:eventDB] retain];
thisEvent.title = #"Title";
thisEvent.startDate = [NSDate date];
thisEvent.endDate = [NSDate date];
thisEvent.calendar = iCloud ;
BOOL saved = [eventDB saveEvent:thisEvent span:EKSpanThisEvent error:&error];
NSLog(#"Saved calendar event = %#\n", (saved ? #"YES" : #"NO"));
[thisEvent release];
thisEvent=nil;
}
[events release];
[eventDB release];
}

Related

Information not being received from server?

Okay, my problem is very simple. Below is my code that is receiving prices from an API, in my code I want the today current price to be displayed, yesterdays price, and the change in percent from yesterday to today. Unfortunately, only the current price is showing properly, but the yesterday and the percent change just show N/A.
Any help is appreciated!
if (refreshing) return;
refreshing = YES;
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
//self.priceLabel.text = #"Loading...";
//self.yesterdayLabel.text = #"Loading...";
//self.changeLabel.text = #"Loading...";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coinbase.com/api/v1/prices/spot_rate"]] queue:[NSOperationQueue mainQueue] completionHandler:^ (NSURLResponse *req, NSData *recv, NSError *err) {
if (err) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSError *newError = nil;
NSDictionary *serial = [NSJSONSerialization JSONObjectWithData:recv options:0 error:&newError];
if (newError) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSString *amount = [serial objectForKey:#"amount"];
NSString *price = [NSString stringWithFormat:#"%# %#", amount, [serial objectForKey:#"currency"]];
[self setCurrentPrice:[NSString stringWithFormat:#"%#", price]];
// maybe setup a better method.
float diff = [yesterdaysPrice floatValue];
if (diff == 0.0)
self.differenceInPrices = #"N/A";
else {
float amt = [amount floatValue];
float percentChange = amt/diff;
if ((diff == 0) || (amt == diff))
percentChange = 0.00;
percentChange *= 100.00;
self.differenceInPrices = [NSString stringWithFormat:#"%f%%", percentChange];
}
NSMutableDictionary *saveState = [[[NSUserDefaults standardUserDefaults] objectForKey:#"save"] mutableCopy];
[saveState setObject:price forKey:#"price"];
[saveState setObject:yesterdaysPrice forKey:#"lastCheckedPrice"];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
[saveState setObject:[NSString stringWithFormat:#"%ld", (usingYesterdaysPrices ? [[saveState objectForKey:#"day"] intValue] : [compon day])] forKey:#"day"];
[[NSUserDefaults standardUserDefaults] setObject:saveState forKey:#"save"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.priceLabel.text =self.currentPrice;
self.yesterdayLabel.text = [NSString stringWithFormat:#"%#", yesterdaysPrice];
self.changeLabel.text = differenceInPrices;
app.networkActivityIndicatorVisible = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"h:mm:ss aa"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
lstUpdate.text = [NSString stringWithFormat:#"Updated: %# at %#", theDate, theTime];
refreshing = NO;
}];
I also have this code in my viewDidLoad,
[super viewDidLoad];
refreshing = NO;
NSDictionary *save = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (save) {
int timeStamp = [[save objectForKey:#"day"] intValue];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
if ([compon day] != timeStamp) {
usingYesterdaysPrices = YES;
yesterdaysPrice = [save objectForKey:#"lastCheckedPrice"];
if (!yesterdaysPrice) {
yesterdaysPrice = #"N/A";
}
}
}
else {
yesterdaysPrice = #"N/A";
}
self.differenceInPrices = #"N/A";
[self sendNewRequest:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(sendNewRequest:) userInfo:Nil repeats:YES];

Some strange error occurs when manipulating events in the calendar of iOS device

I added some events to the calendar and save their eventIdentifier to file. When i want to remove all my events i read the eventIdentifier from that file to an array and remove each event with its event id. Here is the code to add event to calendar and save their event id to file:
- (void) addEventToCalendar: (id)object
{
#autoreleasepool {
int i = 0;
NSString *string_to_file = #"";
eventStore=[[EKEventStore alloc] init];
for(Schedule *sche in scheduleArray){
EKEvent *addEvent=[EKEvent eventWithEventStore:eventStore];
addEvent.title=sche.course_Name;
addEvent.startDate = [self stringToDate:sche.from_Date];
addEvent.endDate = [self stringToDate:sche.thru_Date];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[addEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSDate *date_alarm = [addEvent.startDate dateByAddingTimeInterval:-(10*60)];
addEvent.alarms=[NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:date_alarm]];
NSError *err;
// do save event to calendar
[eventStore saveEvent:addEvent span:EKSpanThisEvent error:&err];
if (err == nil) {
NSString* str = [[NSString alloc] initWithFormat:#"%#", addEvent.eventIdentifier];
string_to_file = [string_to_file stringByAppendingString:str];
string_to_file = [string_to_file stringByAppendingString:#"\n"];
NSLog(#"String %d: %#",i, str);
}
else {
NSLog(#"Error %#",err);
}
i++;
}
// create file to save
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
inFile = [NSFileHandle fileHandleForWritingAtPath: filePath];
NSData *data = [string_to_file dataUsingEncoding:NSUTF16StringEncoding];
[inFile writeData:data];
}
}
And the code below to remove all events i have added to calendar
- (void) deleteEventInCalender {
filemgr = [NSFileManager defaultManager];
NSString *filePath = [self getFilePath:#"saveeventid.txt"];
NSFileHandle *inFile;
inFile = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *dataFile;
dataFile = [inFile readDataToEndOfFile];
NSString *tmp = #"";
NSString *temp = #"";
tmp = [NSString stringWithCharacters:[dataFile bytes] length:[dataFile length]/sizeof(unichar)];
if(![tmp isEqualToString:#""]){
tmp = [tmp substringFromIndex:1];
event_idArray = [[NSMutableArray alloc] init];
int j = 0;
while (![tmp isEqualToString:#""]){
int index_find_string = [tmp rangeOfString:#"\n"].location;
temp = [tmp substringWithRange:NSMakeRange(0, index_find_string)];
[event_idArray addObject:temp];
tmp = [tmp substringFromIndex:index_find_string + 1];
}
EKEventStore* store = [[EKEventStore alloc] init];
j = 0;
for(NSString *eventid in event_idArray){
EKEvent* event2 = [store eventWithIdentifier:eventid];
if (event2 != nil) {
NSLog(#"log: %d log id: %#", j, eventid);
NSError* error = nil;
// remove event
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
j++;
}
[filemgr removeItemAtPath:filePath error:nil];
}
}
All codes above work well when i test on the iOS simulator with calendar.sqlitedb. But it makes some strange errors when i run on iPad device 5.0. That is sometime the calendar not remove event or when all events has been remove then after some minutes all events appear again... I don't understand, i don't know why and i very confuse. Does anyone has the same issue with me? Please share your solution!
Added another question: where the calendar database stored in the iOS 5.0 device.

How to import an iPhone Calendar event to my app?

I am looking for some tutorials/guidelines for importing iPhone calendar event(s) to my app.
Can anyone help?
Thanks
-(void)EventList{
EKEventStore *eventStore = [[EKEventStore alloc] init];
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
ReadCalendar = TRUE;
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- codes here when user allow your app to access theirs' calendar.
[self performCalendarActivity];
}else
{
//----- codes here when user NOT allow your app to access the calendar.
}
}];
}
else {
//---- codes here for IOS < 6.0.
[self performCalendarActivity];
}
}
-(void)performCalendarActivity{
self.eventStore = [[EKEventStore alloc] init];
eventsList = [[NSMutableArray alloc] initWithArray:0];
// Get the default calendar from store.
self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
eventsList= [[self fetchEventsForToday] mutableCopy];
}
-(NSArray *)fetchEventsForToday {
NSDate *startDate;
NSDate *endDate;
startDate = [NSDate date];
endDate = [NSDate dateWithTimeIntervalSinceNow:86400];
// Create the predicate. Pass it the default calendar.
NSArray *calendarArray = [NSArray arrayWithObject:defaultCalendar];
NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate
calendars:calendarArray];
// Fetch all events that match the predicate.
NSArray *events = [self.eventStore eventsMatchingPredicate:predicate];
return events;
}

Why application shows low memory warning during heap shot analysis?

I am developing one application in which recurring transactions are inserted in database.while i am doing heap shot analysis it shows low memory warning while inserting data.its inserting 1200 records approximately.The code for insertion is as below.
-(void)generateReccuringEntry:(int)tranId withAllDate:(BOOL)isAll
{
NSMutableArray *arrDates = [[NSMutableArray alloc] init] ;
NSArray *arr = [[_dicSaveData valueForKey:#"tran_repeatd"] componentsSeparatedByString:#" "];
int day;
if ([self getDayWithDayMonth:[arr objectAtIndex:1]] == 0) {
day = [self getDay:[arr objectAtIndex:1]];
}
else{
day = 1;
}
NSDate *startDate = [_dicSaveData valueForKey:#"tran_date"];
NSString *strEndDate = [NSString stringWithFormat:#"%#",[_dicSaveData valueForKey:#"tran_enddate"]];
NSDate *endDate = nil;
strEndDate = [strEndDate stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
if (![strEndDate stringIsEmpty]) {
endDate = [_dicSaveData valueForKey:#"tran_enddate"];
}
else {
//if end date not selected
endDate = [[startDate dateByAddingYear:1]lastOfYearDate];
}
//get start recurring day
NSString *strDay = [[arr lastObject] stringByReplacingOccurrencesOfString:#"()" withString:#""];
//check start recuring day selected or not
if ([strDay hasPrefix:#"("] && [strDay hasSuffix:#")"])
{
startDate = [self getStartDay:[arr lastObject] withStartingDate:startDate];
if ([startDate compare:endDate]==NSOrderedDescending || [startDate compare:endDate]==NSOrderedSame)
{
SafeRelease(arrDates);
return;
}
if (isAll)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
else{
NSDate *currentDate = [[NSDate date] getDateWithDeviceTimeZone];
if ([startDate compare:currentDate]== NSOrderedDescending)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
}
}
int index = 2;
if (day == 1) {
index = 1;
}
do {
if ([[arr objectAtIndex:index] isEqualToString:#"Week"])
{
startDate = [startDate dateByAddingWeek:day];
}
else if([[arr objectAtIndex:index] isEqualToString:#"Month"])
{
startDate = [startDate dateByAddingMonth:day];
}
else
{
startDate = [startDate dateByAddingDays:day];
}
if (isAll)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
//add recuring for only for future dates
else
{
NSDate *currentDate = [[NSDate date] getDateWithDeviceTimeZone];
if ([startDate compare:currentDate]== NSOrderedDescending)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
}
} while ([startDate compare:endDate]==NSOrderedAscending );
SafeRelease(arrDates);
}
can anyone tell that what is the problem with this code.so that its consuming so much memory?
Update:I have converted app to ARC.but it still shows memory warning.
Highly recommend you convert (if you can) to ARC. The compiler is far more capable of inserting the most efficient retains/releases for you. Would also completely remove any need for anything like SafeRelease.

Manage iPhone Calendar event from our application

The following is my code
NSLog(#"%#", thisEvent1.title);
EKEvent *thisEvent = [EKEvent eventWithEventStore:eventStore];
eventStore = [[EKEventStore alloc] init];
thisEvent = [EKEvent eventWithEventStore:eventStore];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd:HH:mm"];
NSDate * date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:[itsStartDate objectAtIndex:indexPath.row]];
[date retain];
thisEvent.startDate = [dateFormatter dateFromString:[itsStartDate objectAtIndex:indexPath.row]];
thisEvent.endDate = [dateFormatter dateFromString:[itsEndDate objectAtIndex:indexPath.row]];
thisEvent.notes = [itsNotes objectAtIndex:indexPath.row];
thisEvent.title = [itsTitle objectAtIndex:indexPath.row];
thisEvent.location = [itsLocation objectAtIndex:indexPath.row];
// thisEvent.allDay = TRUE;
NSMutableArray *myAlarmsArray = [[NSMutableArray alloc] init];
EKAlarm *alarm1 = [EKAlarm alarmWithRelativeOffset:-[[itsAlertOne objectAtIndex:indexPath.row] intValue]]; // 1 Hour
// EKAlarm *alarm2 = [EKAlarm alarmWithRelativeOffset:-86400]; // 1 Day
[myAlarmsArray addObject:alarm1];
//[myAlarmsArray addObject:alarm2];
thisEvent.alarms = myAlarmsArray;
[myAlarmsArray release];
//setting the Reuccurence rule
NSString * test1 = [itsRecurrenceFrequency objectAtIndex:indexPath.row];
BOOL isRecurrenceFrequencyExists = TRUE;
EKRecurrenceFrequency recurrenceFrequency;
if ([test1 isEqualToString: #"EKRecurrenceFrequencyDaily"]) {
recurrenceFrequency = EKRecurrenceFrequencyDaily;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyWeekly"]){
recurrenceFrequency = EKRecurrenceFrequencyWeekly;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyMonthly"]){
recurrenceFrequency = EKRecurrenceFrequencyMonthly;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyYearly"]){
recurrenceFrequency = EKRecurrenceFrequencyYearly;
}else{
isRecurrenceFrequencyExists = FALSE;
}
if(isRecurrenceFrequencyExists){
EKRecurrenceRule * recurrenceRule = [[EKRecurrenceRule alloc]
initRecurrenceWithFrequency:recurrenceFrequency
interval:[[itsRecurrenceInterval objectAtIndex:indexPath.row]intValue]
end:nil];
if (thisEvent.endDate != nil) {
EKRecurrenceEnd * end = [EKRecurrenceEnd recurrenceEndWithEndDate:thisEvent.endDate];
recurrenceRule.recurrenceEnd = end;
}else {
thisEvent.endDate = thisEvent.startDate;
}
thisEvent.recurrenceRule = recurrenceRule;
[recurrenceRule release];
}
[thisEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:thisEvent span:EKSpanFutureEvents error:&err];
NSLog(#"%#", thisEvent.eventIdentifier);
[self.eventsList addObject:thisEvent];
In this code I have the Event id of my calendar event.
Now I want to update the event with the changes however Its not updating the previously created event.
Second I Need to know is it possible to capture the changes in calendar event they made in iPhone Calendar including deleting an event.
Can we delete the calendar event using the eventid?
Please help me if any one know the answer.. Thank you in advance.
Regards,
Dilip Rajkumar
Event can be created by this:
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSString* str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[arrayofCalIDs addObject:str];
You can delete the event using this:
EKEventStore* store = [[[EKEventStore alloc] init] autorelease];
EKEvent* event2 = [store eventWithIdentifier:[arrayofCalIDs objectAtIndex:i]];
if (event2 != nil) {
NSError* error = nil;
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
[myPath release];
For Updating Event you cannot directly access any method as it is not available in iOS. So, you can do one thing for this.
(1) First remove the event with eventID.
(2) Create new Event using the same information of the last deleted event.