Calling multiple XML files - objective-c

In my application(iPad application) I have 5 folders and inside of each folder i have one XML file. My question is, How can I call all .xml files, in my appDelegate
I have file1.xml, file2.xml, file3.xml, file4.xml,file5.xml (it's a requirement)
for call or adding Path for file1 xml I have this code:
NSString *xml = [[NSBundle mainBundle] pathForResource:#"file1" ofType:#"xml"];
NSData *Data = [NSData dataWithContentsOfFile:xml];
NSXMLParser *Parser = [[NSXMLParser alloc] initWithData:Data];
file1 *parser = [[file1 alloc] initXMLParser];
but how can I have all 5 in my appDelegate class?
and do I need to create specific parser class for each or since all information and tags are the same I just need to add all in my appDelegate
EDIT:
I have to call them from their folder I cann"t change the structure for example
Folder1/file1.xml
Folder2/file2.xml
Folder3/file3.xml and so on

Yes, you need to instantiate an NSXMLParser object for each XML file you're parsing. The simple way to load the XML files is as kimsnarf says: use a for loop and load them in order. If they're in the bundle (which they appear to be), I'd stick them in a specific path under "Resources," like "Resources/SpecialXMLJunk" and just load them by iterating over the results of something like URLsForResourcesWithExtension:subdirectory: (used to get the XML files out of "Resources/SpecialXMLJunk"). So, pseudocode-ish, probably something like this:
NSArray *xmlResourceURLs = [mainBundle
URLsForResourcesWithExtension: #"xml"
subdirectory: xmlResourcesPath];
foreach (NSURL *xmlURL in xmlResourceURLs)
[self loadJunkXMLAtURL: xmlURL];

Create a for-loop and load/parse the files one by one. You should store the parsed data somewhere anyway (in a cache or database) so you don't need to hold on to the files and parsers after parsing. Retrieve data from the cache/database instead.

Related

Extracting Text from url Xcode?

I am new to Objective C.
I was trying to extract text from a webpage and display it in a textView;
Except for when I run the app it appears to show html instead of the article.
NSURL *URL = [NSURL URLWithString:[self.url
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSData *theData = [NSData dataWithContentsOfURL:URL];
NSString *content = [[NSString alloc] initWithData:theData encoding:NSStringEncodingConversionAllowLossy];
_viewPage.text = content;
The viewPage is the textview itself. How do I extract the text only?
You have not included any code to extract the text from the web page. When you run "dataWithContentsOfURL" and it's a web page, then, as you have seen, you get the whole page.
To extract the data you need to process the results. In a simple case you can get the text with some string manipulation. In more complex cases you should look for a library which will parse the whole page for you. You can then access the parsed structure to get the content that you want.
Look here for an example of the simple case;
http://natashatherobot.com/html-css-parser-objective-c/
There are libraries for the more complex case.

how to read content of an XML file from NSOpenPanel

I am trying to copy the content of an XML file after selection from NSOpenPanel in cocoa.
So lets say this XML file could be any where on desktop or other directories. Once I get the file Path, I am trying to read/copy the content to an NSMutableData like following.
I have filePath:
NSString* filePath = [files objectAtIndex:0];
e.g.: file://localhost/Users/Me/Documents/XMLFiles/FileA.xml
Trying to get the content and copy to an NSMutableData
xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
or
xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:filePath]];
If you truly want the data under NSMutableData form then the following should help you:
NSMutableData *theData = [NSMutableData dataWithContentsOfURL:[[theOpenPanel URLs] objectAtIndex:0]];
But I don't think that would be very useful. Why have xml as raw data? Mutable at that!!
Are you looking for the string so you can manually look at the text document?! Then perhaps this is what you're looking for : NSString's stringWithContentsOfFile:encoding:error
Perhaps you want to parse it afterwards?! Then I'd suggest reading on NSXMLParser.

Writing and Reading Objects from Resource Files IOS

I am in the process of making a level editor for my game. I have used cocos2d to make the game. I have a level node that is a subclass of CCNode and contains all the level objects in the game. The level then gets added to a CCLayer. I want to save all the children of the level (an NSMutableArray) to a file in the resources folder. I want to load this NSMutableArray, loop through it, and add all the saved level objects to the level. I can't save these level objects on the local device because the levels in the final game will be based off of this file and other devices need to have it ready along with all the other game resources. Is there any way to do this or do I have to just save strings containing all the properties of the level objects and search through those strings for the information necessary to load the level? If so, is there a way of reading and writing a c structure to a file in combination with an NSString? Here is what I have so far:
NSString * filePath = #"LevelSaves.txt";
NSString * fileRoot = [[NSBundle mainBundle]pathForResource:filePath ofType:#"txt"];
NSString * fileContents = [NSString stringWithContentsOfFile:fileRoot encoding:NSUTF8StringEncoding error:nil];
NSArray * allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
ObjectFactory * objFactory = ObjectFactory::sharedObjectFactory();
for (NSString * curString in allLinedStrings) {
NSArray * seperatedString = [curString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#";"]];
NSString * objectID = (NSString*)[seperatedString objectAtIndex:0];
NSArray * properties = (NSArray*)[seperatedString objectAtIndex:1]; //not really sure about this part. Haven't tried saving anything there yet.
objFactory->createObject(objectID,properties);
You cannot save data in the application bundle (which I believe is what you meant by "resources" folder). You can save them in the app's NSDocumentDirectory, and if your objects conform to NSCoding, you can serialize them using NSKeyedArchiver.
Do the above for debug, and when you're done editing the level, bundle it for release and use NSKeyedUnarchiver to deserialize.

Embedding XML to iOS application

I'm making my first game in iOS and I need to load some levels that are stored as XML. Level files are stored locally and everything works fine from emulator. However, since XML is loaded in the runtime when i try to test my game on an actual device it can't find the XML files since they are not actually part of the app.
I'm coming from Flash background so I might have a wrong idea how this is done on iOS but I need to somehow bundle those XML files with the app, or embed it in the code somehow? Is this possible?
Thanks a lot :)
Well The code to look up your app bundle for the specified file is
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName.xml" ofType:nil]
NSURL *xmlURL = [NSURL fileURLWithPath:path];
[[NSXMLParser alloc] initWithContentsOfURL: xmlURL]
Hope this helps you...
You could add the XML file to your project and run time read it up with something like this
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myPath = [myPathList objectAtIndex:0];
NSError **err;
myPath = [myPath stringByAppendingPathComponent:fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:myPath])
text = [NSString stringWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:err];
You could consider using JSON in instead of XML. At least to my knowledge the available XML parsers are not nearly as simply to use as SBJson for instance (https://github.com/stig/json-framework/)
Here is my solution in Swift 3.0. In addition to the code, you'll need to add your xml file as a data set in your Assets.xcassets. Do this by creating a new Data Set, giving it any name, and then dragging the xml file from the finder to your newly created data set. When you reference the file in your code, you'll use the file name of the file, and not the name of the data set.
var parseResults = false
if let path = Bundle.main.path(forResource: fileName, ofType: ".xml") {
let url = URL(fileURLWithPath: path)
if let xmlParser = XMLParser(contentsOf: urlToFile) {
xmlParser.delegate = self
parseResults = xmlParser.parse()
}
}

File Handling in Objective C

Is there anyway to do Files Handling in Objective-C? I am just trying to do simple read and write and can use 'c' but i am force to use Objective-C classes for that :#. I am looking into NSInputStream, but its going over my head. Is there any tutorial which explains how to use NSInputStream?
I had trouble with basic file i/o when I first hit it in Obj-C as well. I ended up using NSFileHandle to get C style access to my file. Here's a basic example:
// note: myFilename is an NSString containing the full path to the file
// create the file
NSFileManager *fManager = [[NSFileManager alloc] init];
if ([fManager createFileAtPath:myFilename contents:nil attributes:nil] != YES) {
NSLog(#"Failed to create file: %#", myFilename);
}
[fManager release]; fManager = nil;
// open the file for updating
NSFileHandle *myFile = [NSFileHandle fileHandleForUpdatingAtPath:myFilename];
if (myFile == nil) {
NSLog(#"Failed to open file for updating: %#", myFilename);
}
// truncate the file so it is guaranteed to be empty
[myFile truncateFileAtOffset:0];
// note: rawData is an NSData object
// write data to a file
[myFile writeData:rawData];
// close the file handle
[myFile closeFile]; myFile = nil;
If all you need to do is really simple I/O, you can just tell an object to initialize itself from, or write itself to, a filesystem path or URL. This works with several Foundation classes, including NSString, NSData, NSArray, and NSDictionary among others.
Try starting out by looking at the following two NSString methods:
- initWithContentsOfFile:encoding:error:
- writeToFile:atomically:encoding:error:
I find apple's guides short and to the point.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html