How can I join path fragments using objective-C in iOS? - iphone

What's the objective-C equivalent of python's os.path.join in iOS? e.g.:
>>> import os
>>> os.path.join("foo", "bar", "buuxometer", "hi.jpg")
'foo/bar/buuxometer/hi.jpg'

You are looking for [NSString pathWithComponents] which, per the link will:
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.
In your sample:
NSArray *components = [NSArray arrayWithObjects:#"foo", #"bar", #"buuxometer", #"hi.jpg", nil];
NSString *path = [NSString pathWithComponents:components];

Related

Converting an NSArray of Dictionaries to JSON array in iOS

I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray that I have to pass.
array([0] => array('latitude'=>'10.010490',
'longitude'=>'76.360779',
'altitude'=>'30.833334',
'timestamp'=>'11:17:23',
'speed'=>'0.00',
'distance'=>'0.00');
[1] => array('latitude'=>'10.010688',
'longitude'=>'76.361378',
'altitude'=>'28.546305',
'timestamp'=>'11:19:26',
'speed'=>'1.614',
'distance'=>'198.525711')
)`
and the required format is like this
[
{ "latitude":"10.010490",
"longitude":"76.360779",
"altitude":"30.833334",
"timestamp":"11:17:23",
"speed":"0.00",
"distance":"0.00"
},
{
"latitude":"10.010688",
"longitude":"76.361378",
"altitude":"28.546305",
"timestamp":"11:19:26",
"speed":"1.614",
"distance":"198.525711"
}
]
Any one have solution? Thanks in advance.
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"10.010490", #"latitude",
#"76.360779", #"longitude",
#"30.833334", #"altitude",
#"11:17:23", #"timestamp",
#"0.00", #"speed",
#"0.00", #"distance",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstJsonDictionary];
[arr addObject:secondJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
The simplest and best approach !!!
To convert NSArray or NSMutableArray into jsonString you can first convert it into NSData and then further convert that into a NSString. Use this code
NSData* data = [ NSJSONSerialization dataWithJSONObject:yourArray options:NSJSONWritingPrettyPrinted error:nil ];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It helped me and hope it helps you as well. All the best.
I would recommend the SBJson-Framework.
Converting an NSMutableArray is as simple as NSString *jsonString = [yourArray JSONRepresentation];
Edit: Jack Farnandish is right u have to transform it into a NSDictionary before you can convert it to Json. In my example the NSMutableArray has to contain the Dictionary. The Array is only needed to create the square brackets at the beginning and the end of the string.
You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON
First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.
#import <JSONKit/JSON.h>
NSArray *array = // Your array here.
NSString *json = [array JSONString];
NSLog(#"%#", json);
JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.
Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).
Is the service you are calling a RESTful service?
If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.

From PHP to iPhone table

I have a file named numbers.php on my ftp with the following content:
1/Brian/Red
2/Simon/Blue
3/Louise/Red
How do I get that into a table?
I need the table to show:
Brian
Simon
Loiuse
in the cells and then when you click on one of the names it takes you to a page with the colour matching the name.
I use this code when I just need to read a single line in a php file and output to textfields:
NSString *queryString = [NSString stringWithFormat: #"http://website.com/numbers.php"];
NSData *dataRequest = [NSData dataWithContentsOfURL: [ NSURL URLWithString: queryString]];
NSString *serverOutput = [[[NSString alloc] initWithData:dataRequest encoding: NSASCIIStringEncoding] autorelease];
urlTextField.text = serverOutput;
NSArray *splitString = [serverOutput componentsSeparatedByString: #"/"];
NSString *idOut = [splitString objectAtIndex: 0]; NSString *nameOut = [splitString objectAtIndex: 1]; NSString *colorOut = [splitString objectAtIndex: 2];
idTextField.text = idOut; nameTextField.text = nameOut; colorTextField.text = colorOut;
But I am a bit in doubt when it comes to multiple lines and how to get them into my table view. I assume I need to put the lines into an array?
First, I generate plist-Data on the server with the free avaliable CFPropertyList. Why, because it is verry easy to import plist-structures later.
In the app you can import data this way:
NSArray * myArray = [NSArray arrayWithContentsOfURL:[NSURL
URLWithString:#"http://url.com/foo.plist"]];
you can use NSMutableArray instead when you modifing myArray.
cheers

How to selectively trim an NSMutableString?

I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?
Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".
Any help is very much appreciated!
Given that you always need to extract the character upto the first underscore; use the following method;
NSArray *stringParts = [yourString componentsSeparatedByString:#"_"];
The first object in the array would be the extracted part you need I would think.
TESTED CODE: 100% WORKS
NSString *inputString=#"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *array= [inputString componentsSeparatedByString:#"_"];
if ([array count]>0) {
NSString *resultedString=[array objectAtIndex:0];
NSLog(#" resultedString IS - %#",resultedString);
}
OUTPUT:
resultedString IS - MobileSafari
If you know the format of the string is always like that, it can be easy.
Just use NSString's componentsSeparatedByString: documented here.
In your case you could do this:
NSString *source = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *seperatedSubStrings = [source componentsSeparatedByString:#"_"];
NSString *result = [seperatedSubStrings objectAtIndex:0];
#"MobileSafari" would be at index 0, #"2011-09-10-155814" at index 1, and #"Jareds-iPhone.plist" and at index 2.
Try this :
NSString *strComplete = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *arr = [strComplete componentsSeparatedByString:#"_"];
NSString *str1 = [arr objectAtIndex:0];
NSString *str2 = [arr objectAtIndex:1];
NSString *str3 = [arr objectAtIndex:2];
str1 is the required string.
Even if you change MobileSafari to youtube it will work.
So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.
NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]];
See if tis works for you.

Where can I find a CSV to NSArray parser for Objective-C? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'm looking for an easy to use CSV parser for Objective-C to use on the iPhone. Where can I find one?
I'm also looking for other parsers such as JSON, so maybe there is a conversion library somewhere.
I finally got around to cleaning up a parser I've had in my code folder and posted it on Github: http://github.com/davedelong/CHCSVParser
It's quite thorough. It handles all sorts of escaping schemes, newlines in fields, comments, etc. It also uses intelligent file loading, which means you can safely parse huge files in constrained memory conditions.
Here's a simple category on NSString to parse a CSV string that has commas embedded inside quote blocks.
#import "NSString+CSV.h"
#implementation NSString (CSV)
- (NSArray *)componentsSeparatedByComma
{
BOOL insideQuote = NO;
NSMutableArray *results = [[NSMutableArray alloc] init];
NSMutableArray *tmp = [[NSMutableArray alloc] init];
for (NSString *s in [self componentsSeparatedByString:#","]) {
if ([s rangeOfString:#"\""].location == NSNotFound) {
if (insideQuote) {
[tmp addObject:s];
} else {
[results addObject:s];
}
} else {
if (insideQuote) {
insideQuote = NO;
[tmp addObject:s];
[results addObject:[tmp componentsJoinedByString:#","]];
tmp = nil;
tmp = [[NSMutableArray alloc] init];
} else {
insideQuote = YES;
[tmp addObject:s];
}
}
}
return results;
}
#end
This assumes you've read your CSV file into an array already:
myArray = [myData componentsSeparatedByString:#"\n"];
The code doesn't account for escaped quotes, but it could easily be extended to.
Quick way to do this:
NSString *dataStr = [NSString stringWithContentsOfFile:#"example.csv" encoding:NSUTF8StringEncoding error:nil];
NSArray *array = [dataStr componentsSeparatedByString: #","];
Well, above simple solutions doesn't take into account multiple records.
Use the following code reading a default excel CSV using ASCI 13 as line end marker:
NSString *content = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
NSArray *contentArray = [content componentsSeparatedByString:#"\r"]; // CSV ends with ACSI 13 CR (if stored on a Mac Excel 2008)
for (NSString *item in contentArray) {
NSArray *itemArray = [item componentsSeparatedByString:#";"];
// log first item
NSLog(#"%#",[itemArray objectAtIndex:0]);
}
I wrote a dead-simple (although not fully-featured) CSV parser for a project I was working on: CSVFile.h and CSVFile.m. Feel free to grab it -- the code is available under the GPLv3 (unfortunately, it was a requirement for the project I was working on) but I'd be happy to license it to you under an MIT license or another license.
This seems to be the most comprehensive that I've found so far.
http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
As a side note, you'd think most major languages (Delphi, C#, Objective-c, php etc) would have a library available with a full implementation of this basic data interchange format.
I know json is cool and XML is reliable but neither are available as a save option from most applications saving table data. CSV still is.
I've found ParseKit few weeks ago
But IMHO for most cases -[NSString componentsSeparatedByString:] method and NSScanner are more than enough and quite easy to use.
As xmr said above: It's possible in Objective C to convert an NSString csv into 'components separated by string' array.
NSArray* items;
items=[bufferString componentsSeparatedByString:#","];
In case you are interested in csv export having arrived at this thread - as I did - here is an extract of how I exported a csv file.
NSString* fileName = #"Level";
fileName = [fileName stringByAppendingString:levelNumberBeingEdited];
fileName = [fileName stringByAppendingString:#".txt"];
NSString* bufferString=#"";
Buffer String is populated by looping through each data item (not shown) and inserting a comma between each. Finally it's exported.
NSString* homeDir = NSHomeDirectory();
NSString* fullPath = [homeDir stringByAppendingPathComponent:fileName];
NSError* error = nil;
[bufferString writeToFile:fullPath atomically:NO encoding:NSASCIIStringEncoding error:&error];

How do I parse a text file in Objective-C?

I need to parse a text file, one line at a time. Also, is there EOF in Objective-C?
Something like this might work for you:
NSString *fileContents = [NSString stringWithContentsOfFile:#"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
This will give you an array where each element is a line of the string.
Objective-C is a proper extension of C. Any C program is a valid Objective-C program. Among other things, this means that EOF defined in the standard C header "stdio.h" is an EOF marker in Objective-C as well.
stringWithContentsOfFile is deprecated.
Here is an updated answer:
NSError* error;
NSString *fileContent = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:&error];
NSArray *lines = [fileContent componentsSeparatedByString:#"\n"];