parsing XML located inside the project - ios

This is the first time i'm going to parse an XML file with Xcode and it differs a bit from what I'm used to...
I read these 2 docs :
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html#//apple_ref/doc/uid/20002265-BCIJFGJI
I understand what's going on... But I still got one question. How can I do to parse an XML file which is located directly inside the project (I mean, for example in the resource file, where I usually put my images?). They usually show how to get the url of the XML file..But it's not the case here. It's going to be loaded directly on the iPad, among images and everything...

You Simply have to give the path of a local file :-
NSString *myFile= [documentsDirectory stringByAppendingPathComponent:#"youFile.xml"];
NSURL *xmlFile = [NSURL fileURLWithPath:myFile];
NSXMLParser *parser= [[NSXMLParser alloc] initWithContentsOfURL:xmlFile];
This is just an example implement your own login , use above two lines to get the path of local file.

Related

Can't read data that was written with writeToFile:atomically

I have these 2 lines of code:
[[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://somepath.com/first.plist"]] writeToFile:#"first.plist" atomically:YES];
NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"first" ofType:#"plist"]];
But my dTmp is null. I'm not specifying any path, so it's supposed to be stored in the root directory, right?
What is my mistake?
There are a couple of problems with your code.
You should not use synchronous networking calls like dataWithContentsOfURL. it willl block the UI. Look at NSURLSession instead.
You can't write to a file in the root directory. iOS apps are limited to a few sandbox directories like the apps' documents and caches directories.
You should write code that writes and reads to one of your allowed sandbox directories.
Also, don't write compound statements. It makes it hard to read and debug. Do one thing on each line.
Check the return value at each step to see what's going wrong.

iOS cannot parse KML / XML downloaded from server

A KML file I include in the project parses correctly whereas the same file downloaded from a server does not?!
I modified Apple's KML parsing example to parse a KML file. If I add the KML file directly into the Xcode project it parses correctly and displays it's polylines, annotations, etc. on the map as expected. But if I download the same KML file from my server, save it to disk and attempt to parse it, the parsing does not work. i.e. the parser does not find any elements to parse in the file so nothing is displayed on the map!
Firstly I have verified that the file downloads and saves to disk correctly. I checked the simulator's data (SimPholders is a handy tool for this) to get the file and compare it to the original one in case of corruption, no problem there, it downloads and saves correctly, no corruption.
I next checked the URL to the file I pass to the KML parser to ensure that it is correct and it was fine. I used NSFileManager fileExistsAtPath to determine this, the KML file is at the path I provide to the parser.
In the map view controller's viewDidLoad method I download the file from the server and pass it to the parser.
- (void)viewDidLoad
{
[super viewDidLoad];
[[KmlDownloader sharedKmlDownloader] downloadFileFrom:#"http://www.myserver.com/file.kml" isAsyncDownload:NO];
NSURL *kmlUrl = [[KmlDownloader sharedKmlDownloader] urlForKmlFile];
if (kmlUrl)
{
kmlParser = [[KMLParser alloc] initWithURL:kmlUrl];
[kmlParser parseKML];
}
// Add all of the MKOverlay objects parsed from the KML file to the map.
NSArray *overlays = [kmlParser overlays];
[map addOverlays:overlays];
// Add all of the MKAnnotation objects parsed from the KML file to the map.
NSArray *annotations = [kmlParser points];
[map addAnnotations:annotations];
// Some positioning code of the view port here
}
KmlDownloader as a reference can be found as a Gist here. Sorry the formatting was messing up too much to include inline, its a relatively small file though.
Any ideas why this may be happening? Many thanks.
Ok found the issue. It was to do with how I was accessing the file once downloaded. Once saved to disk I would send it's URL to the parser. The problem was I was using the incorrect NSURL method, I was originally using:
NSURL *fileUrl = [NSURL URLWithString:[self pathForFile:self.pathToKmlFileOnDisk]];
Whereas I should have been using:
NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:self.pathToKmlFileOnDisk];
Both are the same URL but the second one includes the "file:///" prefix. Once changed the parser would parse as expected.

Write content of NSURL to an array

I have a program that retrieves data from a link and i write it out to the Log like this.
NSURL *getURL=[NSURL URLWithString:#"link.php"];
NSError *error=nil;
NSString *str=[NSString stringWithContentsofURL:getURL encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%",str);
This prints to the log the three values from my php as expected.
However I am having a little difficulty saving this in an array which then displays it those values in a UISplitviewController (the leftcontroller side).
which is written like this
showArray=[[NSMutableArray alloc]initWithContentofURL:getURL];
then in cellForRowAtIndexPath: method is
cell.textLabel.text=[showArray object atIndex:indexPath.row];
A second thing i have tried is write myURL to an array and tried to initlize showArray with ContentsofArray like this
NSArray *retults=[NSArray arraywithContentsOFURL:getURL];
showArray=[[NSArray alloc]initWithArray:retults];
but THAT dont work
BUT if i say
showArray=[[NSMutableArray alloc]initWithObjects:#"One",#"Two",nil];
One and two shows in my leftview controller....
Would love is someone could help me with this...Thank you
Are you trying to add the contents of the URL or the URL itself ?
If you are trying to just add the URL, then use :
showArray = [#[getURL] mutableCopy];
However, if you are trying to add the contents of the URL, then the doc clearly states that the URL must represent a string representation of an array.
Furthermore :
Returns nil if the location can’t be opened or if the contents of the location can’t be parsed into an array.
EDIT :
I saw your comment on your post and your data looks like JSON data.
You should take a look at the NSJSONSerialisation class which is pretty straightforward to use (you'll find lots of example here on SO).
U have done web services perfectly, now wat u have to do is parse it to an array
First download the SBJSON files in this link
https://github.com/stig/json-framework/
Then, copy them to your workspace.
Then, in the viewController add this
#import "SBJson.h"
Your JSON data contains values in the form of dictionary
SO, to parse them
SBJsonParser * parser=[SBJsonParser new];
NSDictionary * jsonData=(NSDictionary *)[parser objectWithString:outputData];
NSArray * arr=(NSArray *)[NSDictionary objectForKey:#"animal"];
I think this will help

Getting Image URLs in a Web Directory

I want to get URLs of all images or lets say "JPEG" files in a web directory (www.abcde.com/images). I just want their URLs in an array.. I couldnt manage that. Could u pls help me with this?
Thanks in advance..
Assuming you have access to an index file you could simply load via NSURL the whole html file and cut out the link lines. This however will not work (or hardly work) when you want to search ("spider or crawl") for links in more complex documents. On iOS i would suggest you use the simple, yet quite powerfull "hpple" framework (https://github.com/topfunky/hpple). It is used to parse html. You can search with it for certain html elements, such as <a href...> constructs.
a sample with hpple could looks like this:
NSURL *url = [NSURL URLWithString:#"whatver.com/images"];
NSData *data = [NSData url];
TFHpple *hppleParser = [TFHpple data];
NSString *images = #"//img"; // grabbs all image tags
NSArray *node = [hppleParser searchWithXPathQuery:images]
find a bigger example at http://www.raywenderlich.com/14172/how-to-parse-html-on-ios
Create a server side script(eg php) which gives you a list of all images in that directory as xml or json. From iOS send a request to that script get the xml or JSON parse it and use the image urls.

Recommended way of testing for CSS file type in iOS?

Is there a recommended way of testing for CSS file type in iOS?
I am asking for the NSURLTypeIdentifierKey thus:
NSError *err = nil;
NSString *uti = nil;
NSURL *fileURL = [NSURL fileURLWithPath:path];
[fileURL getResourceValue:&uti forKey:NSURLTypeIdentifierKey error:&err];
This works for most filetypes that I've tried it on, and I get back one of the Uniform Type Identifiers listed in the System-Declared Uniform Type Identifiers reference. I can test for RTF, etc, like this.
I noticed that for a CSS file I get back a UTI of “dyn.ah62d4rv4ge80g65x” though. I thought perhaps my CSS file had some odd metadata, so I cut and paste its contents into a brand new file in VI, and the UTI for that file came back the same.
I then did "cat /dev/null > empty.css" and tested the UTI of that empty file and it too came back with “dyn.ah62d4rv4ge80g65x”, so clearly this UTI is being derived from the file extension.
I don't see any mention of “dyn…” UTIs in the reference. Can I rely on this odd string?
Usually this indicates a dynamic UTI, that is one that the system creates on the fly as it is not part of its database. In such case you probably have to examine other attributes like file extension or look inside the file.

Resources