Download remote server xml to local(only update is available) - iphone

I have an XML file that is going to live on our server. The first time I request an url and download it locally for use within my app. it's working.if the download is available only means we are again go to url and download.
, I compare the local time stamp to the remote file time stamp and only re-download it if the time stamp is newer (e.g. it has been updated).
I am using http post method.If the download is not available i can cancel connection.else..download the server data and update the last modified date to local xml.
Is it correct or any other better way to check
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse httpResponse = (NSHTTPURLResponse)response;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
BOOL check=[self checkUpdate:[[httpResponse allHeaderFields] objectForKey:#"Last-Modified"]];
NSLog(#"%#",[dictionary description]);
if (!check) {
[connection cancel];
[delegate display];
}
}
-(BOOL) checkUpdate:(NSString*) str
{
self.lastmodified=str;
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//
self.cachedPath = [NSString stringWithFormat:#"%#/%#",docDir,self.refxml];
fileManager = [NSFileManager defaultManager];
lastModifiedServer = [[NSDate date] retain];
#try {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = #"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[lastModifiedServer release];
lastModifiedServer = [[df dateFromString: self.lastmodified]retain];
[df release];
}
#catch (NSException * e) {
NSLog(#"Error parsing last modified date: %# - %#", self.lastmodified, [e description]);
}
NSDate *lastModifiedLocal = nil;
if ([fileManager fileExistsAtPath:self.cachedPath]) {
NSError *error = nil;
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:cachedPath error:&error];
lastModifiedLocal = [fileAttributes fileModificationDate];
if ([lastModifiedLocal laterDate:lastModifiedServer] == lastModifiedServer) {
return YES;
}
else
{
return NO;
}
}
else
{
return YES;
}
return YES;
}

Related

XMPP resource id getting change while login more then one device

i have logged in two devices with same user id and password, so when destination device send voice or image to client .The one device getting the destination message but another one device not getting the destination message . because the resource id is getting change when login in two devices. Its showing error message 503()
(NSString *)full
{
if (user)
{
if (resource)
{
//----- here i am getting the resource ID -------
[[NSUserDefaults standardUserDefaults]setObject:resource forKey:#"GETRESOURCE"];
[[NSUserDefaults standardUserDefaults]synchronize];
return [NSString stringWithFormat:#"%##%#/%#", user, domain, resource];
}
else
{
return [NSString stringWithFormat:#"%##%#", user, domain];
}
} else {
if (resource)
return [NSString stringWithFormat:#"%#/%#", domain, resource];
else
return domain;
}
}
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
CGFloat maxCompression = 0.1f;
NSData *imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], maxCompression);
[messageType addObject:#"1"];
//---- now implementing the resource id here i getting 503 Error----
NSString *resourceStr = [[NSUserDefaults standardUserDefaults] valueForKey:#"GETRESOURCE"];
XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:#"%#/%#", receiver, resourceStr]];
[fileTransfer initiateFileTransferTo:jid withData:imageData];
self.willSendImage = [UIImage imageWithData:imageData];
[messageArray addObject:[NSDictionary dictionaryWithObject:self.willSendImage forKey:#"image"]];
[self.timestamps addObject:[NSDate date]];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
[dbHandler insertChatHistory:#"image" imageData:imageData receiveType:2 mediaType:2 receiverName:titleName date:dateString];
[self finishSend];
[JSMessageSoundEffect playMessageSentSound];
[self scrollToBottomAnimated:YES];
[self reloadMessages];
[self dismissViewControllerAnimated:YES completion:NULL];
}
//--- I WILL SEND THE IMAGE AS A STRING FORMET ITS WORKED FOR ME
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
CGFloat maxCompression = 0.1f;
UIImage * getimage =[self imageWithImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
NSData *imageData = UIImageJPEGRepresentation(getimage, maxCompression);
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
//--- convert image to string -----
NSString* imageString = [imageData base64EncodedStringWithOptions:0];
//---- new change --
imageString = [imageString stringByAppendingString:#".IMAGE"];
//-------------
if ([imageString length] > 0)
{
[dbHandler insertChatHistory:imageString imageData:nil receiveType:2 mediaType:1 receiverName:titleName date:dateString];
NSXMLElement *body = [NSXMLElement elementWithName:#"body"];
[body setStringValue:imageString];
NSXMLElement *message = [NSXMLElement elementWithName:#"message"];
[message addAttributeWithName:#"type" stringValue:#"chat"];
[message addAttributeWithName:#"to" stringValue:receiver]; //--- jenish ---
[message addChild:body];
[self.xmppStream sendElement:message];
[messageType addObject:#"1"];
[messageArray addObject:[NSDictionary dictionaryWithObject:imageString forKey:#"Text"]];
[self.timestamps addObject:[NSDate date]];
}
[self finishSend];
[JSMessageSoundEffect playMessageSentSound];
[self scrollToBottomAnimated:YES];
[self reloadMessages];
[self dismissViewControllerAnimated:YES completion:NULL];
}

Unable to either attach or create a .csv file (using CHCSVParser)

I am having a problem either attaching or creating a .csv file in my app, I cannot figure out where the problem exists. In the email view the .csv attachment is shown but when the email is received it has no attachment. I send an array of objects (dataController.masterList) to the CHCSVWriter. I've spent a lot of time this week trying solutions from other questions regarding email attachments and CHCSVWriter and obviously none of the solutions have worked so know I'm asking you. Where does the problem exist, and what do you suggest?
Thank you in advance,
Happy Days, -Rob
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSString *filepath = #"testfile.csv";
filepath = [filepath stringByExpandingTildeInPath];
NSOutputStream *exportStream = [NSOutputStream outputStreamToFileAtPath:filepath append:NO];
NSStringEncoding encodingA = NSUTF8StringEncoding;
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithOutputStream:exportStream encoding:encodingA delimiter:','];
[csvWriter writeField:[NSString stringWithFormat:#"One"]];
[csvWriter writeLineOfFields:dataController.masterList];
[csvWriter closeStream];
NSString *path = [[NSBundle mainBundle] pathForResource:filepath ofType:#".csv"];
NSData *mydata = [NSData dataWithContentsOfFile:path];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
[mail addAttachmentData:mydata mimeType:#"text/csv" fileName:filepath];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
I figured it out, I stopped using the CHCSV writer and just wrote an array then combined the components of the array with a ",".
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSIndexPath *index2 = 0;
NSUInteger i = 0;
NSString *holder;
NSArray *holderArray;
NSArray *saverArray;
while (i < dataController.countOfList) {
TimeSheetEntry *sAtIndex = [self.dataController objectInListAtIndex:index2.row];
NSString *dayhold = [formatter stringFromDate:sAtIndex.date];
holderArray = [[NSArray alloc] initWithObjects:sAtIndex.name, sAtIndex.jobnum, sAtIndex.hours, sAtIndex.jobnotes, dayhold, nil];
saverArray = [saverArray arrayByAddingObjectsFromArray:holderArray];
i++;
NSIndexPath *index3 = [NSIndexPath indexPathForRow:i inSection:1];
index2 = index3;
}
holder = [saverArray componentsJoinedByString:#","];//this is the seperating variable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *outputFile = [docDirectory stringByAppendingPathComponent:#"timesheet.csv"];
NSError *csvError = NULL;
BOOL written = [holder writeToFile:outputFile atomically:YES encoding:NSUTF8StringEncoding error:&csvError];
if (!written)
NSLog(#"write failed, error=%#", csvError);
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
//[mail setMessageBody:holder isHTML:YES];
[mail addAttachmentData:[NSData dataWithContentsOfFile:outputFile] mimeType:#"text/csv" fileName:#"timesheet.csv"];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
For anyone that still wants to use CHCSVParser, I found that the file path has to be absolute:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Task"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
NSURL *datapath = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"export.csv"];
NSOutputStream *output = [NSOutputStream outputStreamToMemory];
CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:output encoding:NSUTF8StringEncoding delimiter:','];
// Fetch objects to write to .csv
for (Task *task in fetchedObjects) {
[writer writeLineOfFields:#[task.taskID, task.taskTitle, task.taskDescription]];
}
entity = [NSEntityDescription entityForName:#"Journal"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
for (JournalEntry *entry in fetchedObjects) {
[writer writeLineOfFields:#[entry.day, entry.entryTitle, entry.entryDescription]];
}
[writer closeStream];
NSData *buffer = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[buffer writeToURL:datapath atomically:NO];

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.

Reading a Text file in xcode

First off, I'm a complete beginner.
This might be a stupid question, but here it goes:
I'm currently working on an App than contains Latin texts that the users can view and read.
I'm using Xcode 4 with the storybord function.
Theway the app is built: user selects author - then the book - then app shows the text.
I am kind of confused because i need to have various text files, depending on the users choice.
As i have done or do usually just embedded the files as resource and by using the below code I read-out the files
in .h file
-(NSString *)readFile:(NSString *)fileName;
in .m file
-(NSString *)readFile:(NSString *)fileName
{
NSLog(#"readFile");
NSString *appFile = fileName;
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSString *resultData = [NSString stringWithContentsOfFile: appFile encoding: NSUTF8StringEncoding error: &error];
if (error == NULL)
return resultData;
}
return NULL;
}
May this will help you
Enjoy Coding :)
EDIT
What I have done is according to the date change on one button click and also at the time of viewWillApper I call the function below
-(void)dateAndContentReload
{
NSLog(#"dateAndContentReload");
NSLog(#"Appdelegate Date: %#",appDelegate.dateSelected);
self.currentDate = appDelegate.dateSelected;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MMMM yyyy"];
NSString *dateString = [dateFormatter stringFromDate: appDelegate.dateSelected];
self.navigationItem.title = dateString;
[dateFormatter setDateFormat: #"Myyyy"];
NSString *dateComp = [dateFormatter stringFromDate: appDelegate.dateSelected];
//NSLog(#"date : %#",dateString);
NSString *data;
NSString *path;
if(![dateComp isEqualToString: #"12012"])
{
NSString *size = [NSString stringWithFormat: #"%f",appDelegate.size] ;
NSLog(#"dateAndContentReload size: %f",appDelegate.size);
data = #"<html><body><font size='";
data = [data stringByAppendingString: size];
data = [data stringByAppendingString: #"'><P>"];
data = #"Data not Available for Current Date.";
data = [data stringByReplacingOccurrencesOfString: #"\n" withString:#"<br>"];
data = [data stringByAppendingString:#"</P></font></body></html>"];
}
else
{
[dateFormatter setDateFormat:#"MMMMd"];
dateString = [dateFormatter stringFromDate: appDelegate.dateSelected];
[dateFormatter release];
NSLog(#"new Format: %#",dateString);
path = [[NSBundle mainBundle] pathForResource: dateString ofType: #"txt"];
data = nil;
NSString *size = [NSString stringWithFormat: #"%f",appDelegate.size] ;
NSLog(#"dateAndContentReload size: %f",appDelegate.size);
data = #"<html><body><font size='";
data = [data stringByAppendingString: size];
data = [data stringByAppendingString: #"'><P>"];
data = [data stringByAppendingString: [self readFile: path]];
data = [data stringByReplacingOccurrencesOfString: #"\n" withString:#"<br>"];
data = [data stringByAppendingString:#"</P></font></body></html>"];
}
[self.currentView loadHTMLString: data baseURL: nil];
}
Basically I read file and display in UIWebView as client request it.

How to delete files from iPhone's document directory which are older more than two days

I have an App in which I record the sound files and store it in apps Document Directory.
What I want is, it should contain only yesterday and to days older files and remove all others from the folder in iPhone app. Is there any way to do this?
Thanks ..
Please look at the following code.
//Get the Document directory path.
#define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
//Delete files by iterating items of the folder.
NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:kDOCSFOLDER];
NSError* err = nil;
BOOL res;
NSString* file;
while (file = [en nextObject]) {
// Date comparison.
NSDate *creationDate = [[fm attributesOfItemAtPath:file error:nil] fileCreationDate];
NSDate *yesterDay = [[NSDate date] dateByAddingTimeInterval:(-1*24*60*60)];
if ([creationDate compare:yesterDay] == NSOrderedAscending)
{
// creation date is before the Yesterday date
res = [fm removeItemAtPath:[kDOCSFOLDER stringByAppendingPathComponent:file] error:&err];
if (!res && err) {
NSLog(#"oops: %#", err);
}
}
}
If you would have searched little you would have got this:
[fileManager removeItemAtPath: fullPath error:NULL];
So you can get creation date of your file using something like this:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSDictionary* dict = [fileManager attributesOfItemAtPath:filePath error:nil];
NSDate *date = (NSDate*)[dict objectForKey: NSFileCreationDate];
Compare those date in if condition and delete those files.
UPDATE 1: Working code to delete files which are older than two days.
// Code to delete images older than two days.
#define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
NSFileManager* fileManager = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fileManager enumeratorAtPath:kDOCSFOLDER];
NSString* file;
while (file = [en nextObject])
{
NSLog(#"File To Delete : %#",file);
NSError *error= nil;
NSString *filepath=[NSString stringWithFormat:[kDOCSFOLDER stringByAppendingString:#"/%#"],file];
NSDate *creationDate =[[fileManager attributesOfItemAtPath:filepath error:nil] fileCreationDate];
NSDate *d =[[NSDate date] dateByAddingTimeInterval:-2*24*60*60];
NSDateFormatter *df=[[NSDateFormatter alloc]init];// = [NSDateFormatter initWithDateFormat:#"yyyy-MM-dd"];
[df setDateFormat:#"EEEE d"];
NSString *createdDate = [df stringFromDate:creationDate];
NSString *twoDaysOld = [df stringFromDate:d];
NSLog(#"create Date----->%#, two days before date ----> %#", createdDate, twoDaysOld);
// if ([[dictAtt valueForKey:NSFileCreationDate] compare:d] == NSOrderedAscending)
if ([creationDate compare:d] == NSOrderedAscending)
{
if([file isEqualToString:#"RDRProject.sqlite"])
{
NSLog(#"Imp Do not delete");
}
else
{
[[NSFileManager defaultManager] removeItemAtPath:[kDOCSFOLDER stringByAppendingPathComponent:file] error:&error];
}
}
}
Please check following code for swift :
func cleanUp() {
let maximumDays = 2.0
let minimumDate = Date().addingTimeInterval(-maximumDays*24*60*60)
func meetsRequirement(date: Date) -> Bool { return date < minimumDate }
func meetsRequirement(name: String) -> Bool { return name.hasPrefix(applicationName) && name.hasSuffix("log") }
do {
let manager = FileManager.default
let documentDirUrl = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
if manager.changeCurrentDirectoryPath(documentDirUrl.path) {
for file in try manager.contentsOfDirectory(atPath: ".") {
let creationDate = try manager.attributesOfItem(atPath: file)[FileAttributeKey.creationDate] as! Date
if meetsRequirement(name: file) && meetsRequirement(date: creationDate) {
try manager.removeItem(atPath: file)
}
}
}
}
catch {
print("Cannot cleanup files: \(error)")
}
}
Please check following code:
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] error:nil];
for (NSString *file in dirContents) {
NSError *error= nil;
NSDictionary *dictAtt = [[NSFileManager defaultManager] attributesOfItemAtPath:/*file path*/ error:&error];
NSDate *d =[[NSDate date] dateByAddingTimeInterval:-86400];
if ([[dictAtt valueForKey:NSFileCreationDate] compare:d] == NSOrderedAscending) {
[[NSFileManager defaultManager] removeItemAtPath:/*file path*/ error:&error];
}
}