IOS: read txt file when I launch an app - ios

Everytime I launch an app, I should to read 5 txt file where are stored some information; then the methods that read and stored data in array from these file should be write in my firstview controller (class of my first view) or in class appdelegate?

In the relevant view controller (probably viewDidLoad).
It would look something like this (untested):
- (void)viewDidLoad {
NSArray *fileNames = [NSArray arrayWithObjects:#"fileName1.txt", #"fileName2.txt", #"etc", nil];
NSMutableArray *fileStrings = [[NSMutableArray alloc] init];
for (int i = 0; i<[fileNames count]; i++) {
NSString *aFileName = [fileNames objectAtIndex:i];
NSString *aFilePath = [[NSBundle mainBundle] pathForResource:aFileName];
NSString *aFileContents = [[NSString alloc] initWithContentsOfFile:aFilePath];
[fileStrings addObject:aFileContents];
[aFileContents release];
}
myStrings = fileStrings; // Some array to store to
}

I am guessing this is configuration info that you are reading. I would suggest using a pList instead of using text files.
Apple has really optimized reading from & to a plist. Hope this helps...

Related

Adding score and current date to plist

I have to retain the score and current date for a game in a plist . I created a dictionary with two arrays:
- (void)viewDidLoad
{
[super viewDidLoad];
dateArray=[[NSMutableArray alloc]init];
scoreArray=[[NSMutableArray alloc]init];
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];
[self getDate];
NSString *path = [[NSBundle mainBundle] pathForResource:#"score" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
int lastItemIndex = scoreArray.count;
[scoreArray insertObject:[dict objectForKey:#"scoreElements"] atIndex:lastItemIndex];
}
-(IBAction) saveData
{
NSString *plistPath =[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"Score.plist"];
NSMutableArray* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
[plistDict setValue:self.scoreLabel.text forKey:#"scoreElements"];
[plistDict writeToFile:plistPath atomically: YES];
}
This code is good only for the last game played, but I want to fill the tableView with the old scores as well. How can I do it?
Instead of using
[scoreArray insertObject:[dict objectForKey:#"scoreElements"] atIndex:lastItemIndex];
why don't you use
[scoreArray addObject: dict["scoreElements"];
Also when you are saving using below code, it will always set new value to "scoreElements" overriding old ones.... so you have to use array as well.
[plistDict setValue:self.scoreLabel.text forKey:#"scoreElements"];
You could use NSUserDefaults to store stuff and retrieve it later on.
Check out the reference about this class at Apple :
nsuserdefault apple

Adding list of URLs to an array?

I'm using MHVideoPhotoGallery to create gallery's of images that are stored on my website. The current way to add images (as shown in the example on Github) is
MHGalleryItem *photo1 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
MHGalleryItem *photo2 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
MHGalleryItem *photo3 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
self.galleryDataSource = #[#[photo1,photo2,photo3]];
But I want to add hundreds of images and this is not the most ideal way to do it. What would be an easier way for me to accomplish this?
Thanks!
You have to start with a list of the URLs. What I would do is put this in a text file in my bundle. In code, when the app runs, I would open the text file (as an NSString) and split it into an NSArray. Now I've got an NSArray of the URLs. I would then cycle through the NSArray. So now we're inside a loop. For each item the array, I would initialize the MHGalleryItem and then add it to a previously created NSMutableArray with addObject:. Thus we have a two or three-line loop which is repeated, running through all the URLs.
The following is pseudo-code and untested (so it might contain errors), but it should give the general idea of the structure I'm suggesting:
NSMutableArray* temp = [NSMutableArray new];
NSString* s =
[NSString stringWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:#"urls" ofType:#"txt"]
encoding:NSUTF8StringEncoding error:nil];
NSArray* urls = [s componentsSeparatedByString:#"\n"];
for (NSString* url in urls) {
MHGalleryItem *item = [[MHGalleryItem alloc] initWithURL:url
galleryType:MHGalleryTypeImage];
[temp addObject:item];
}
self.galleryDataSource = temp;
Loop. If you're putting numbers at the end of your variable names, you need a loop and/or an array.
NSMutableArray * photos = [NSMutableArray new];
NSArray * photoPaths = [NSArray arrayWithContentsOfFile:plistContainingPhotoPaths];
for( NSString * path in photoPaths ){
NSURL * photoURL = [NSURL URLWithString:path];
MHGalleryItem * photo = [[MHGalleryItem alloc] initWithURL:photoURL
galleryType:MHGalleryTypeImage];
[photos addObject:photo];
}
And don't use dot syntax for alloc, or your code will burst into flames.
Use a naming protocol on your website such as:
www.mywebsite.com/appImageGallery/insertImageNumber
And replace the insertImageNumber with the number of you image. Then add this for loop to get all of the images and add them to the array.
NSMutableArray *mutableGalleryDataSource = [self.galleryDataSource mutableCopy]
for(int i = 0; i < numberOfImagesOnWebsite; i++){ //replace numberOfImagesOnWebsite with the number of images on your website.
MHGalleryItem *newItem = [MHGalleryItem.alloc initWithURL:[#"www.mywebsite.com/appImageGallery/" stringByAppendingString:[NSString stringWithFormat: #"%i", i]] galleryType:MHGalleryTypeImage];
[mutableGalleryDataSource addObject:newItem];
}
self.galleryDataSource = mutableGalleryDataSource;
There is also an -addObjectsFromArray method on NSMutableArray.

IOS library to convert powerpoint presentations into images

after a lot of searching and still searching, i'm unable to find the way to extract the slides out of powerpoint presentations. Need help, if they know anything related this or have implemented such thing, source code will be great or any reference link will also work. I have been using QLPreviewController, but i failed to override it.
I am not sure whether this is still required. but anyways, this is how I have implemented
(1) Use UIWebView to display the content of the PPT. The well formed (!) HTML allows you to parse it. Get the html using
NSString *htmlContent = [self.webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
(2) Count the number of div class = 'slide to get the slide count
(4) You need to parse the HTML to get the styles and div using the below code
(5) Get all the styles
- (NSString *)getStyles:(int)slideCount forView:(UIWebView *)view {
NSString *getElementByTag = [[NSString alloc] init];
NSString *allStyles = [[NSString alloc] init];
for (int i = 0; i < slideCount; i++) {
getElementByTag = [NSString stringWithFormat:#"document.getElementsByTagName('style')[%d].innerHTML", i];
NSString *style = [[view stringByEvaluatingJavaScriptFromString:getElementByTag] stringByAppendingString:#"\n"];
allStyles = [allStyles stringByAppendingString:style];
}
allStyles = [#"<style type='text/css'>" stringByAppendingString: allStyles];
return [allStyles stringByAppendingString:#"</style>"];
}
(6) Concatenate all the styles from step 5 with div tag content. Define a NSMutableArray variable to to store all slides with styles for future reference. Define NSMutableArray *slides to store all the slides
- (void)makeSlides:(int)slideCount forView:(UIWebView *)view {
self.slides = [[NSMutableArray alloc] init];
for (int i = 0; i < slideCount; i++) {
NSString *slideBody = [NSString stringWithFormat:#"document.getElementsByClassName('slide')[%d].innerHTML", i];
NSString *div = [view stringByEvaluatingJavaScriptFromString:slideBody];
NSString *slide = [self.slideStyles stringByAppendingString:div];
[self.slides addObject:slide];
}
}
Hope this helps

uiswitch in uitableview persistence when close and reopen the app? [duplicate]

This question already has answers here:
NSUserDefault and Switches
(2 answers)
Closed 9 years ago.
I would like to ask about uiswitch in uitableview custom cell.
if I have array that keeps state of each uiswitch in the table and update it on Change Value Event.However this changes are not persistence each time i open the app it reset to it's initial state. My question is how to make the changes persistent on my app whenever i close it and reopen it again ?
Here is my change value code:
-(void)switchChanged:(UISwitch *)sender
{
UITableViewCell *cell = (UITableViewCell *)[sender superview];
NSIndexPath *x=[mainTableView indexPathForCell:cell];
NSMutableArray *repl = [[NSMutableArray alloc] init];
if (sender.on)
{
repl= [SwitchArray objectAtIndex:x.section] ;
[repl replaceObjectAtIndex:x.row withObject:#"ON"];
}
else
{
//call the first array by section
repl= [SwitchArray objectAtIndex:x.section] ;
[repl replaceObjectAtIndex:x.row withObject:#"OFF"];
}
}
Here is the initial values of the array in viewDidLoad:
for(int j=0 ; j < 30 ; j++)
[switchArray addObject:#"ON"];
Thanks in advance. I appreciate your collaboration This will make me happy
One easy way to persist the array between uses of the app is to write out the array to a pList.
In order to do so you'll need a place to store the file, take the following example:
- (NSURL *)switchArrayFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *filePath = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:#"SwitchArray.plist"]];
return filePath;
}
Then in order to load up your array, you can read the pList back in in viewDidLoad: for instance:
self.switchArray = [[NSMutableArray alloc] initWithContentsOfURL:[self switchArrayFilePath]];
Then in order to write out the data, you could so something like this in viewWillDisappear:
[self.switchArray writeToURL:[self switchArrayFilePath] atomically:YES];
Other ways to persist this type of data on iOS would be use NSUserDefaults or use Core Data but that would be complex for something simple like this.
Hope that helps!

Access a variable outside the method in objective-c

I have this function that is storing the contents of an array in three different variables. My question is how can I access to the contents stored in _company.address from another function in the same class.
-(NSArray *) csvArray2CompaniesArray:(NSArray *) csvArray
{
int i=0;
NSMutableArray *ma = [[NSMutableArray alloc] init];
for (NSArray * row in csvArray)
{
if (i>0)
{
Company *_company = [[Company alloc] init];
_company.name = [row objectAtIndex:0];
_company.address = [row objectAtIndex:1];
_company.telephone = [row objectAtIndex:2];
[ma addObject:_company];
}
i++;
}
return (NSArray *) ma;
}
Thank you in advance.
You cannot the accessibility of an object is private in a function.Either you declare it as global or declare it in class's scope.Better in .h file
You can use the functios value as :-
YourViewControllerWithFunction *accessFunc=[[YourViewControllerWithFunction alloc]]init];
Company *_company=[accessFunc csvArray2CompaniesArray:youInputArray];
[_company objectAtIndex:intVallue];//Use in loop
You should correct the return value of your function to NSMutableArray or make a copy to get the NSArray of the NSMutableArray you created.
After that, you can access the contents of your array from anywhere inside your class like:
for (Company *c in [self csvArray2CompaniesArray:csvarray])
{
NSLog(#"%#", c.address);
}

Resources