Reading a Text file in xcode - iphone

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.

Related

Memory issue on Loading images from Photo Library and sort them datewise

I am fetching images from my photo library and according to assets's date property , I am arranging those images in a different folders . What I want to do is to fetch the image from photo library , store them according to date . e.g. if fetched image is from 23rd April, store them in "April" folder . I am using WSAssetPickerController for this. Please help me in solving memory issue as my app crashes due to the memory issue on device, this works fine in simulator.
- (void)storePhotos:(NSArray *)assets {
int index = 0;
for (ALAsset *asset in assets) {
NSLog(#"Current asset :%# ",asset);
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMMM dd, yyyy"];
NSString *photoDate = [format stringFromDate:[asset valueForProperty:ALAssetPropertyDate]];
resourceDocPath = [resourceDocPath stringByAppendingPathComponent:photoDate];
// Create directory & Check directory
BOOL checkDir = [self createDocumentDirectory:resourceDocPath fileName:asset.defaultRepresentation.filename];
if (!checkDir) {
continue;
}
// Write image
NSString *writablePhotoPath = [resourceDocPath stringByAppendingPathComponent:asset.defaultRepresentation.filename];
[self writeImage:writablePhotoPath WithImage:asset.defaultRepresentation.fullScreenImage];
index++;
}
}
- (void)writeImage:(NSString*)pstrPhotoPath WithImage:(CGImageRef)pImage {
if (![[NSFileManager defaultManager] fileExistsAtPath:pstrPhotoPath]){
UIImage *image = [[UIImage alloc] initWithCGImage:pImage];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:pstrPhotoPath atomically:YES];
}
}
- (BOOL)createDocumentDirectory:(NSString*) pCurrentFolder fileName:(NSString*) pStrFileName {
if (![[NSFileManager defaultManager] fileExistsAtPath:pCurrentFolder]){
if ([self checkPhotoIsExistInDocument:pStrFileName]) {
return FALSE;
}
NSError* error;
if ([[NSFileManager defaultManager] createDirectoryAtPath:pCurrentFolder withIntermediateDirectories:NO attributes:nil error:&error]) {
// success
return TRUE;
} else {
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
return TRUE;
}
return TRUE;
} else {
return TRUE;
}
}
- (BOOL)checkPhotoIsExistInDocument:(NSString*) pStrImageName {
NSString *bundleRoot = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
// NSLog(#"%#", filename);
if ([filename hasSuffix:pStrImageName]) {
return TRUE;
}
}
return FALSE;
}
Are you using ARC in your project? Because you have not released any objects which you are allocating and initializing.
resourceDocPath
format
image
bundleRoot
Should be released as soon as their use is over. Also if you can provide the logs of your application crash that would be very useful.

how to use 'string' variable as 'objectForkey' in iphone

I want to use string as objectForkey. my code line is this.
And I want to use "strend" as a objectForkey but it didn't work.
Code is:
NSString *strend = [[NSString alloc] initWithFormat:#"%#",[[detwec.arrdetails objectAtIndex:0]valueForKey:#"EndDate"]];
NSString *dateString = [[NSString alloc]initWithFormat:#"%#",[_currentItemValue objectForKey:#"strend" ]];
try to replace this line
NSString *dateString = [[NSString alloc]initWithFormat:#"%#",[_currentItemValue objectForKey:#"strend" ]];
by this
NSString *dateString = [[NSString alloc]initWithFormat:#"%#",[_currentItemValue objectForKey:strend]];
if you want to read a value using string as key you can use:
NSString *value = ["Your Dictionary" objectForKey:strend];
get a check that your NSString *strend shouldn't be "nil" else will not give you any value.
You Can Try
NSString *strend = [NSString stringWithFormat:#"%#",[detwec.arrdetails objectAtIndex:0]valueForKey:#"EndDate"];
NSString *dateString = [NSString stringWithFormat:#"%#",[_currentItemValue objectForKey:#"strend" ]];
or else
NSString *dateString = [_currentItemValue objectForKey:#"strend" ];
NSString *strend = [NSString stringWithFormat:#"%#",[detwec.arrdetails objectAtIndex:0]]; NSUserDefaults *storeData=[NSUserDefaults standardUserDefaults];
[storeData setObject:strend forKey:#"strend"];
NSString *dateString = [storeData objectForKey:#"strend"];

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

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;
}

How to print a NSString using AirPrint?

Im having real trouble with this one. I dont know what is wrong, but it spits this out:
ERROR: attempting to display print options with no printing source(item/items/formatter/renderer) set
The code works if i set it to print a png image, but not the contents of a NSString.
Here is my code:
- (IBAction)pushPrint:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setDateFormat:#"dd/MM/YY HH:mm:ss"];
NSString* currentTime = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSString *path = [[NSBundle mainBundle] pathForResource:t[NSString stringWithFormat:#"Results Printout\n"
"\n"
"%#\n"
"\n"
"\n"
"%#", currentTime, pasteboard.string] ofType:nil];
NSData *myData = [NSData dataWithContentsOfFile:path];
UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
print.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [path lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
print.printInfo = printInfo;
print.showsPageRange = YES;
print.printingItem = myData;
void (^completionHandler)(UIPrintInteractionController *,BOOL, NSError *) = ^(UIPrintInteractionController *print,BOOL completed, NSError *error) {
if (!completed && error) {
NSLog(#"houston we have a problem");
}
};
[print presentAnimated:YES completionHandler:completionHandler];
}
You seem to be wanting to print a plain NSString, yet you are trying to load a file with a file path that cannot be valid. Thus, myData is very likely nil (please confirm with the debugger) and thus the error message is correct (print.printingItem must not be nil).
To print a simple text, create an instance of UISimpleTextPrintFormatter (with initWithText:) and assign that instance to print.printFormatter.

UIImagePickerController Save to Disk then Load to UIImageView

I have a UIImagePickerController that saves the image to disk as a png. When I try to load the PNG and set a UIImageView's imageView.image to the file, it is not displaying.
Here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(image);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png",
[dateFormatter stringFromDate:[NSDate date]]];
[dateFormatter release];
// Find the path to the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:NO];
// Set the managedObject's imageLocation attribute and save the managed object context
[self.managedObject setValue:fullPathToFile forKey:#"imageLocation"];
NSError *error = nil;
[[self.managedObject managedObjectContext] save:&error];
[self dismissModalViewControllerAnimated:YES];
}
Then here is how I try to load it:
self.imageView.backgroundColor = [UIColor lightGrayColor];
self.imageView.frame = CGRectMake(10, 10, 72, 72);
if ([self.managedObject valueForKey:#"imageLocation"] != nil) {
NSLog(#"Trying to load the imageView with: %#", [self.managedObject valueForKey:#"imageLocation"]);
UIImage *image = [[UIImage alloc] initWithContentsOfFile:[self.managedObject valueForKey:#"imageLocation"]];
self.imageView.image = image;
} else {
self.imageView.image = [UIImage imageNamed:#"no_picture_taken.png"];
}
I get the message that it's trying to load the imageView in the debugger, but the image is never displayed in the imageView. Can anyone tell me what I've got wrong here?
Thanks a bunch.
You're writing out an NSData object, not an image. You need to read the NSData object back in and convert to UIImage.
Assuming everything else is correct, try this:
NSData *data = [[NSData alloc] initWithContentsOfFile:[self.managedObject valueForKey:#"imageLocation"]];
UIImage *image = [[UIImage alloc] initWithData:data];
Using NSDateFormatterShortStyle will cause the date to be represented as (for example) 12/11/12, which will mess up your file name. It will also use a colon in the short time representation, which is illegal.
I would recommend using a more custom date format, such as:
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:#"yyyyMMdd-HHmmss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
I used this code on one of my test projects and simulated the bug. Jordan was right about converting it to NSData first before changing it again to UIImage but the real problem here is on your file naming method.
I noticed that you have used the current date and time as the file name of your image. This includes characters such as ":" and "/" which is not allowed to be used on file names. http://www.portfoliofaq.com/pfaq/FAQ00352.htm
As a solution, I made the date format as what is written below:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMddHHmm"];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png",
[dateFormatter stringFromDate:[NSDate date]]];
Hope this helps others as well. :)