(iPhone) Reading from a web file - NSMutableArray - iphone

Right now I have an NSArray whose items are just written in the implementation file.
I'd like to know how to make it so I can store all the items on a web (text) file. Example:
http://mysite.com/files/objects.txt
On that document:
Object 0 goes here
Object 1 goes here
Object 2 goes here
Object 3 goes here
etc. All separated by a line break.
How would I be able to do this? And when I update that text file, I'd like the objects to update as well. I'd do this via an NSMutable array, correct?
Thanks in advance.

- (NSArray*)getObjectsFromWeb {
NSURL *url = [NSURL URLWithString:#"http://mysite.com/files/objects.txt"];
NSStringEncoding usedEncoding;
NSError *error;
NSString *data = [NSString stringWithContentsOfURL:url
usedEncoding:&usedEncoding
error:&error];
return [data componentsSeparatedByString:#"\n"];
}
after data is assigned here, usedEncoding (and possibly error) will have a value that you can inspect and tak action on if you like.

Related

escape character not convert properly when calling webservice in iPhone app...?

I'm using JSON web service to collect data and display in my UITableView cell. My problem is when I try to call my web service, if the data has characters like & it gives me &.
When I try to store this JSON data in NSDictionary and after that display in UITableView cell it appear as it is.
Eg. if data is Chris & Priscilla originally it retrieves as Chris & Priscilla and same shows in my cell. I want to display it as Chris & Priscilla and not Chris & Priscilla.
It displays properly in browser.
I can't find what I missed.
NSError *error = nil;
NSString *strUrl = #"MY-WEBSERVICE-URL";
NSURL *url = [[NSURL alloc] initWithString:strUrl];
NSString *returnText = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
txt.text = returnText;
Usually HTML unescaping is done adding a category to NSString. There are many examples, i.e. here: http://google-toolbox-for-mac.googlecode.com/svn/trunk/Foundation/GTMNSString+HTML.h.
Particularly, have a look at
(NSString *)gtm_stringByUnescapingFromHTML;

How to parse this type of data ios sdk [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
parse UTF-8 JSON ios sdk
[4,"1.0",1347139911696]
[0,"Neathouse Place","58226","STBC",154,"L",51.495322,-0.141808]
[0,"Vauxhall Bridge Rd / Victoria Stn","59516","STBC",160,"Z9",51.495931,-0.142216]
[0,"VICTORIA, VAUXHALL BRIDGE ROAD (EAST)",null,null,0,null,51.495839,-0.142119]
[0,"Vauxhall Bridge Rd / Victoria Stn","54249","STBC",256,"M",51.496573,-0.141354]
How to parse this type of data.
check this link.
It is UTF-8 JSON data type according to service provider. If its not then please tell me which type of data is it and how to parse it.
please help me out.
thanks.
The first thing to realize is that your data is actually 5 separate but valid JSON arrays. JSON can be validated at jsonlint.com.
To make something useful from them you must split your response by lines. You can use the newline character as a delimiter.
// stringWithContentsOfURL: used for demonstration
NSURL *sourceURL = [NSURL URLWithString:#"http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?Circle=51.49598,-0.14091,100&StopPointState=0&ReturnList=StopCode1,StopPointName,Bearing,StopPointIndicator,StopPointType,Latitude,Longitude"];
NSString *actualResponse = [NSString stringWithContentsOfURL:sourceURL encoding:NSUTF8StringEncoding error:nil];
NSArray *individualJSONArrays = [actualResponse componentsSeparatedByString:#"\n"];
You now have an NSArray with 5 valid JSON NSStrings. You can either deal with any one of them, or convert them all to NS-Class objects by enumerating like so:
NSMutableArray *jsonObjects = [[NSMutableArray alloc] init];
for (NSString *jsonString in individualJSONArrays) {
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
if (jsonArray){
[jsonObjects addObject:jsonArray];
}
}
NSLog(#"%#",jsonObjects);
You now have an NSArray filled with NSArrays.

Removing // from NSMutableArray

When I NSLog the contents of an NSMutableArray I get null. I believe I know what the issue is.
I'm having a bit of trouble trying to figure out how to remove "//" at the beginning of this JSON output. If you load http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL,C into your browser you'll see the "//" at the beginning. I believe that the "//" is what is causing the array to return null. How could I go about removing the two dashes? Below is I have what I've done thus far...
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSLog(#"json is %#", json); //returns "json is (null)"
You can try this:
NSData *newData = [data subdataWithRange:NSMakeRange(4, [data length] -4)];
This gets rid of the first four characters. There was a control character the two slashes and a space before the first "[", and this gets rid of those. I tried this but the data still had a flaw in it further on.

Fetch XML of Distance Matrix API (google) on iPhone

I'm trying to fetch the XML data from a query to the api without success...
I'm doing this:
[...]
NSURL *googleAPIurl = [NSURL URLWithString:#"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=28.124822,-15.430006&destinations=28.126953,-15.429874|28.072056,-15.416574|28.103186,-15.417665|28.127916,-15.625403|28.099125,-15.418365|28.107740,-15.454050|28.050825,-15.454066|28.051640,-15.454104|28.101788,-15.423592|28.113750,-15.446980|28.098871,-15.420730|28.098217,-15.449371|28.083364,-15.418172&mode=driving&sensor=false"];
NSData *xmlData = [NSData dataWithContentsOfURL:googleAPIurl];
NSError *error;
GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (xmlDocument == nil)
{
NSLog(#"NIL XML");
}
[...]
I'm ALWAYS getting a nil XML. NSData is always nil. I don't know what is happening with this. If I use a url with one destination only it works, but not for more than one. Also, I'm using the same method to retrieve xml with google places api with no problems. This is driving me crazy...
Please point me in the right direction.
Thanks in advance.
I suggested replacing all of the '|' with '%7C'
Turns out this is the more proper method to cover all of these character encoding issues:
NSURL *googleAPIurl = [NSURL URLWithString:[distancesURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Load remote csv into CHCSVParser

I am using Dave DeLong's CHCSVParser to parse a csv. I can parse the csv locally, but I cannot get it load a remote csv file. I have been staring at my MacBook way too long today and the answer is right in front of me. Here is my code:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"];
NSURL *lunchFileURL = [NSURL URLWithString:urlStr];
NSStringEncoding encoding = 0;
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVFile:[lunchFileURL path] usedEncoding:&encoding error:nil];
[p setParserDelegate:self];
[p parse];
[p release];
Thanks for any help that someone can give me.
-[NSURL path] is not doing what you're expecting.
If I have the URL http://stackoverflow.com/questions/4636428, then it's -path is /questions/4636428. When you pass that path to CHCSVParser, it's going to try and open that path on the local system. Since that file doesn't exist, you won't be able to open it.
What you need to do (as Walter points out) is download the CSV file locally, and then open it. You can download the file in several different ways (+[NSString stringWithContentsOfURL:...], NSURLConnection, etc). Once you've got either the file saved locally to disk or the string of CSV in memory, you can then pass it to the parser.
If this is a very big file, then you'll want to alloc/init a CHCSVParser with the path to the local copy of the CSV file. The parser will then read through it bit by bit and tell you what it finds via the delegate callbacks.
If the CSV file isn't very big, then you can do:
NSString * csv = ...; //the NSString containing the contents of the CSV file
NSArray * rows = [csv CSVComponents];
That will return an NSArray of NSArrays of NSStrings.
Similar to this last approach is using the NSArray category method:
NSString * csv = ...;
NSError * error = nil;
NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:[csv fastestEncoding] error:&error];
This will return the same structure (an NSArray of NSArrays of NSStrings), but it will also provide you with an NSError object if it encounters a syntax error in the CSV file (ie, malformed CSV).
I think you need an NSString, not an NSURL object to pass to the parser so the extra part you are doing with changing the NSString to an NSURL is the issue. Looking at the CHCSVParser documentation, it looks like he wants NSString in the init.
So maybe you could do something like:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];