View Image array from web folder in iOS - ios

I want to be able to view images from a web folder inside my iPhone app. I know how to view the images with a specific url (i.e. www.mywebsite.com/image.jpg). That's easy. I just don't know how to asynchronously load an array. Basically I need to view images with a specific sequence (i.e. mywebsite.com/image_001.jpg, image_002.jpg, image_003.jpg, etc). There may be 10 or 100 images in a folder with that sequence. How do I let my app load images with a sequence?

Following code will sort images of this file format "imageName_number.jpg"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *webDir=[documentsDirectory stringByAppendingPathComponent:#"WebFolder"];
NSFileManager *filemgr;
NSMutableArray *fileNum;
fileNum=[[NSMutableArray alloc]init];
filemgr = [NSFileManager defaultManager];
//This will give all files of your web directory you can uncomment to get dynamically
//NSArray *filelist = [filemgr contentsOfDirectoryAtPath: webDir error: nil];
// this is just example shows how unsorted will be used to sort image no you can comment this line
NSArray *filelist=[[NSArray alloc]initWithObjects:#"abc_001.jpg",#"def_005.jpg",#"abc_002.jpg",#"abc_0103.jpg",#"abc_0010.jpg",#"abc_008.jpg", nil];
int count = (int)[filelist count];
NSMutableDictionary *dictFileNumWithPath=[[NSMutableDictionary alloc]init];
NSString *imageSeprator=#"_";
for (int i = 0; i < count; i++){
NSString *imageName=[filelist objectAtIndex: i];
if (!([imageName rangeOfString:imageSeprator].location == NSNotFound)) {
NSRange startRange = [imageName rangeOfString:imageSeprator];
NSRange endRange = [imageName rangeOfString:#".jpg"];
NSRange searchRange = NSMakeRange( startRange.location+1, endRange.location-endRange.length);
NSString *strNum= [imageName substringWithRange:searchRange];
NSString *webPath=[webDir stringByAppendingPathComponent:imageName];
[dictFileNumWithPath setObject:[NSNumber numberWithInt:[strNum intValue]] forKey:webPath];
}
}
NSArray *sortedKeysFilePathArray =
[dictFileNumWithPath keysSortedByValueUsingSelector:#selector(compare:)];
NSLog(#"%#", sortedKeysFilePathArray);

Related

How to write array data into excel file (CSV) in objective c

I am trying to write the array data into excel (actually it is a CSV, but it is opened in excel). I used the following code to do that:
NSMutableArray *list;
list = [[NSMutableArray alloc] init];
NSString *string = [list componentsJoinedByString:#","];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"yourFileName.csv"];
[data writeToFile:appFile atomically:YES];
It works fine, but the problem is I have 20 objects in my 'list' array and all those 20 objects are written in side by side cells. What I want is to write the first 4 objects in one line and then move to the new line and again write the next 4 objects in that line till all the objects in the list array are completed.
Can anyone help me with this issue?
NSMutableArray *list = ...
NSMutableString *buffer = [NSMutableString string];
for (NSUInteger i = 0; i < list.count; i++) {
NSString *value = list[i];
if (i > 0) {
if (i % 4 == 0) { //after every 4th value
buffer.append("\n"); //end line
}
else {
buffer.append(",");
}
}
buffer.append(value);
//if your values contain spaces, you should add quotes around values...
//buffer.appendFormat(#"\"%#\"", value);
}
NSData *data = [buffer dataUsingEncoding:NSUTF8StringEncoding];
...
To break lines in CSV just input a \r\n in the "end of the line". Be caerfull because in the mac you only need \r or \n (not really sure right now)

count items in plist array

I am having difficult accessing the count of a chosen plist. In the previous view controller, the user selects from one of several buttons, each one corresponding to a particular plist. That plist is sent to the current vc as NSString * chosenPlist. I have NSLogged to see that the documents directory and the plistpath seem to be correct, but the array that I want to count is still 0.
How can I count the number of items in the chosen plist?
NSString * chosenPlistPlus = [chosenPlist stringByAppendingString:#".plist"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"The documentsdirectory is %#", documentsDirectory);
NSString *myPlistPath = [documentsDirectory stringByAppendingPathComponent:chosenPlistPlus];
NSLog(#"MyPlistPath = %#", myPlistPath);
NSArray *arr = [NSArray arrayWithContentsOfFile: myPlistPath];
//Trying to count the items in the plist, which is an array of dicts.
int count = arr.count;
NSLog(#"Count is %i", count);
here is a log:
2013-11-16 21:13:07.037 GlobalHistoryRegents[70407:70b] The documentsdirectory is /Users/username/Library/Application Support/iPhone Simulator/7.0.3/Applications/896EF347-A35E-40E2-9BE1-8CFAC5303347/Documents
2013-11-16 21:13:07.037 GlobalHistoryRegents[70407:70b] MyPlistPath = /Users/username/Library/Application Support/iPhone Simulator/7.0.3/Applications/896EF347-A35E-40E2-9BE1-8CFAC5303347/Documents/methodologyQuestions.plist
2013-11-16 21:13:07.038 GlobalHistoryRegents[70407:70b] Count is 0
try using,
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:myPlistPath];
NSArray *arr =dictionary[#"Root"];

Objective-C Download PLIST and use within table

I'm fairly new to Objective-C programming. I'm trying to build an app for personal use to view event info which is contained on my web server. I wish for each Event Title string to be shown as a separate row within my UITableView.
I'm using CFPropertyList to create the plist from MySQL. Here's what my plist looks like:
I'm downloading the plist like so:
NSString *stringURL = #"http://www.example.com/events.plist";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"events.plist"];
[urlData writeToFile:filePath atomically:YES];
}
Then this is how I'm trying to load the info into their arrays:
events = [[NSDictionary alloc] initWithContentsOfFile:filePath];
ID = [events objectForKey:#"Event ID"];
title = [events objectForKey:#"Event Title"];
date = [events objectForKey:#"Event Date"];
price = [events objectForKey:#"Price"];
totalTickets = [events objectForKey:#"Total Tickets"];
ticketsSold = [events objectForKey:#"Tickets Sold"];
ticketsRemaining = [events objectForKey:#"Tickets Remaining"];
postStatus = [events objectForKey:#"Post Status"];
postContent = [events objectForKey:#"Post Content"];
Now here's where I'm having trouble. Now when I'm debugging the number of rows the 'events' dictionary has it returns 0.
Therefore I cannot set the 'numberOfRowsInSection'. Nor does [title objectAtIndex:indexPath.row] work.
I believe the issue lays with how I'm setting up the NSDictionary, but due to my lack of Objective-C and array knowledge, I'm unable to overcome this issue.
Here's your problem:
events = [[NSDictionary alloc] initWithContentsOfFile:filePath];
Your plist is an array of dictionaries and you're trying to load that array as a dictionary. Try this instead:
events = [NSArray arrayWithContentsOfFile:filePath];
Edit: To extract the titles into an array so you can use them in table cells, do this:
NSMutableArray *titles = [NSMutableArray array];
for (NSDictionary *event in events) {
NSString *title = [event objectForKey:#"Event Title"];
[titles addObject:title];
}

how to insert a Dictionary into an array

I am quite new to iOS and Objective-c.
I am trying to auto generate a pList in my app that looks like this.
I've so far been able to create the file making it a normal Value => Key file if i replace my for loop by
for (NSString* exercisePictureName in bigPictureData) {
[data setObject:exercisePictureName forKey:exercisePictureName];
}
but my problem is that I have no idea how to structure the logic at the end of my loop to create a file structure like shown in the picture. As it has to be exact.
Could anyone point me in the right direction on how to structure my loop so that it creates the file with the right format????
- (void) createImageListFromSource {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"exercisePictures.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: #"exercisePictures.plist"] ];
}
//To insert the data into the plist
NSArray* bicepPictureData = [self getAllimagesThatStartWith:#"bicep-"];
NSArray* tricepPictureData = [self getAllimagesThatStartWith:#"tricep-"];
NSArray* absPictureData = [self getAllimagesThatStartWith:#"abs-"];
NSArray* chestPictureData = [self getAllimagesThatStartWith:#"chest-"];
NSArray* backPictureData = [self getAllimagesThatStartWith:#"back-"];
NSArray* bigPictureData = [bicepPictureData arrayByAddingObjectsFromArray:tricepPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:absPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:chestPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:backPictureData];
NSArray* finalData = [[NSArray alloc] init];
for (NSString* exercisePictureName in bigPictureData) {
NSDictionary* data = [[NSDictionary alloc] initWithObjectsAndKeys:exercisePictureName,#"text",exercisePictureName,#"image", nil];
[finalData arrayByAddingObject:data];
NSLog(#"%#",data);
}
NSLog(#"%#",finalData);
[finalData writeToFile: path atomically:YES];
}
What you have is an array of dictionaries. Pseudocode to show the structure:
NSMutableArray* arr = [NSMutableArray array];
for (...) {
NSDictionary* d = #{#"image": something, #"text": somethingelse};
[arr addObject:d];
}
When you are all done, just save the array directly with writeToURL....

IOS: problem to synchronize nsarray with string

I have a NSArray in this way
myArray[0] = [string1, string2, string3, string4, mySecondArray, string5]; (at 0 position)
I write this array inside a txt file in this way
NSString *outputString = #"";
for (int i = 0; i< myArray.count; i++){
outputString = [outputString stringByAppendingString:[[[myArray objectAtIndex:i ] componentsJoinedByString:#"#"] stringByAppendingString:#";"]];
}
NSLog(#"string to write = %#", outputString);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Text.txt"];
NSError *error;
[outputString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
then the result of NSLog is = (position 0 of myArray) (mySecond array is empty)
one#two#three#four#(
)#five;
I want to know:
Why the array wrap?
When I'll go to read this string how can I know that it's mySecondArray?
When you message componentsJoinedByString: on an NSArray object, it calls description on each of its objects and concatenates them in order. For NSString objects, they are the strings themselves. The array wraps because of the way the description method has been implemented.
As for identifying the array while you are reading the string back, I don't think it is possible. You should consider writing the array to the file rather i.e.
[[myArray objectAtIndex:0] writeToFile:filePath atomically:YES];
or
[myArray writeToFile:filePath atomically:YES];
depending on the requirement. This way you will be able to read the elements back properly.

Resources