I am currently using NSURLConnection to download some date from a database through a php script on a server.
The connection works fine and data is received correctly. However I have a problem when I come to parse the data.
I am currently trying to use the NSXMLParser to parse the data however this is failing with Error code 4, I think this is because what I retrieve is not entirely XML. If it is entirely XML it works.
Here is an example of the data retrieved :
43534545-45345345-34534554|iPhone emulator|<provdoc>
<characteristic type="P1">
...
</characteristic>
</provdoc>
And what I'd like to do is split the data into:
43534545-45345345-34534554
and:
iPhone emulator
and
<provdoc>
<characteristic type="Profile1">
...
</characteristic>
</provdoc>
So Im guessing that I should do that in the following function where I take in the data, I need to know how I split the data into the above three sections?
So I end up with two strings, the first one with the numbers and the second with the iPhone emulator bit and then the data that can be send through the NSXMLParser.
Can anyone point me in the right direction as yo what I need yo accomplish that?
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
}
Convert the final NSData to an NSString:
NSString *someString = [[NSString alloc] initWithData:hashedData encoding:NSUTF8Encoding];
Then you'll need to start splitting up that string. Here's an example of getting the first portion:
NSRange end = [someString rangeOfString:#"<"];
NSString *str = [someString substringWithRange:NSMakeRange(0, end.location)];
Then split up the first one:
NSArray *initialItems = [str componentsSeparatedByString:#"|"];
You should be able to figure out the rest with the above techniques.
Related
I am facing a peculiar problem in parsing some xml data within my iPhone application. When I pass the xml data to NSXMLParser class for parsing, it ignores the part where the actual data starts appearing. It shows all the element names just before the data appears such as Soapenvolopebody etc. Later, I observed that the tags are appearing with '<'; and '>';symbols which is causing the problem.
I hope this requires a replacement strategy before parsing it to NSXMLParser. My questions is why iPhone is taking XML in that way? I am generating xml dynamically from a php file and comes as an XML when loaded into IE Browser. Hope you can help me to resolve the issue.
Update
I am still looking for a solution. I think the the idea of converting NSString to NSData and then passing it to NSXMLParser could accomplish parsing.
NSString* str= #"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
I found this mentioned in the following post which I will be trying out. How do I convert an NSString value to NSData?
Update 1
I get the data in NSData format. Converted to NSString and applied replacement code to done away with < and > stuff. After that, I again converted the replaced NSString to NSData format. But still the xml is not correctly parsing using NSXMLParser.
please replace the unwonted character using this string function. please refer the below code.
NSString *theXML = [[[NSString alloc] initWithBytes: [webdata mutableBytes] length:[webdata length] encoding:NSUTF8StringEncoding]autorelease];
theXML = [theXML stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
theXML = [theXML stringByReplacingOccurrencesOfString:#">" withString:#">"];
theXML = [theXML stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSLog(#"%#",theXML);
Thanks
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
separating keys and objects from NSMutable dictionary and use the values in insert command of sqlite
I have an NSDictionary containing parsed JSON data. How can I push these data to a database so that I can extract them from database for further use?
I am using SBJSON for parsing.
If your design requirements specify sqlite, then I would recommend using Gus Mueller's FMDB so that you do not have to work directly with raw sqlite.
NSString $title = [jsonDictionary objectForKey:#"title"];
// other keys, values, etc...
NSString $query = [NSString stringWithFormat:#"INSERT INTO myTable t (t.some_column) VALUES ('%#'),$title];
FMResultSet *results = [_db executeQuery:$query];
That said, as Chris said above, Core Data is often a better solution than sqlite. Brent Simmons (NetNewsWire developer) has a series of posts about this subject, like this one.
The exception to the "Core Data is better than sqlite" mantra for me is the situation where you want to provide initial data but do not want to perform an initial import into Core Data.
Use core data for this matter. Here is a good tutorial to start with:
http://mobile.tutsplus.com/tutorials/iphone/iphone-core-data/
Following code goes to create the dynamic plist file and that file stores into the bundle and that data can be access and the insert the data into the .plist file.
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#/%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
#"data.plist"];
NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
NSLog([dOfAudios allKeys].count>0?#"Value is exist":#"Value is not exist");
if([dOfAudios allKeys].count>0) {
[dOfAudios setValue:#"Key_for_value" forKey:#"value_for_key"];
} else {
dOfAudios=[NSMutableDictionary dictionary];
[dOfAudios setValue:#"Key_for_value" forKey:#"value_for_key"];
}
[dOfAudios writeToFile:strPathToAudioCache atomically:YES];
I'm implementing CHCSVParser into my iPhone app (thanks Dave!) however I'm really confused on how to use it. I've read the read-me and searched some questions on SO but still not 100% sure what to do.
I have a .CSV file with maybe 5000 rows of data and 3-4 columns.
I want this data to in return, load my UITableView along with its corresponding detailViewController.
So I'm assuming I need to somehow implement the API's array method but can anyone help get me started?
I'm glad you like it :)
Basically, CHCSVParser only parses CSV files. You give it a path to a CSV file, and it'll give you back a whole bunch of NSStrings. What you do beyond that point is entirely up to you.
So let's say you've included a CSV file in your iOS app called "Data.csv". Here's how you'd use CHCSVParser to parse it:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"csv"];
NSError *error = nil;
NSArray *rows = [NSArray arrayWithContentsOfCSVFile:path encoding:NSUTF8StringEncoding error:&error];
if (rows == nil) {
//something went wrong; log the error and exit
NSLog(#"error parsing file: %#", error);
return;
}
At this point, rows is an array. Each element in rows is itself an array representing a single row in the CSV file. And each element of that array is an NSString.
So let's say your CSV file looks like this:
Barringer,Arizona,United States,Earth
"Chicxulub, Extinction Event Crater",,Mexico,Earth
Tycho,,,Moon
Lonar,Maharashtra,India,Earth
If you run it through the parser, you'll get back the equivalent of this:
[NSArray arrayWithObjects:
[NSArray arrayWithObjects:#"Barringer",#"Arizona",#"United States",#"Earth",nil],
[NSArray arrayWithObjects:#"Chicxulub, Extinction Event Crater",#"",#"Mexico",#"Earth",nil],
[NSArray arrayWithObjects:#"Tycho",#"",#"",#"Moon",nil],
[NSArray arrayWithObjects:#"Lonar",#"Maharashtra",#"India",#"Earth",nil],
nil];
What you do with it then is your business. The CSV parser doesn't know anything about UITableView, so you get to take this data and re-structure it in a way that you're comfortable dealing with and that fits in to your data model.
Also, remember that by using CHCSVParser, you agree to abide the terms under which it is made available. :)
I am aware this question has been asked several times, but I was unable to find a definate answer that would best fit my situation.
I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.
This is what I have so far:
NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
[picker dismissModalViewControllerAnimated:YES];
NSString *content = [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
NSLog(#"%#", content);
The NSLog statement simply produces output as:
2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)
Obviously this isnt what I hoped to achieve, so any help would be great.
Kind Regards
You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.
Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.
How do I use comma-separated-values received from a URL query in Objective-c?
when I query the URL I get csv such as ("OMRUAH=X",20.741,"3/16/2010","1:52pm",20.7226,20.7594).
How do I capture and use this for my application?
You have two options:
Use a CSV parser: http://freshmeat.net/projects/ccsvparse
Or parse the data yourself into an array:
// myString is an NSString object containing your data
NSArray *array = [myString componentsSeparatedByString: #","];
I recently dealt with CSV parsing for Yahoo! Finance as well. I used Ragel to write a parser in C that was good enough for the CSV I was getting. It handled everything but escaped quotes, which are not going to show up much in stock quotes. It was pretty painless and a good learning experience. I'd post the code, but it was work-for-hire, so I don't own it.
Turning a C string into an NSString is easy. If you have it as an NSData, as you likely do at the end of a URL download, just do [[NSString alloc] initWithData:csvData encoding:NSUTF8StringEncoding]. If you have a pointer to a character buffer instead, use [[NSString alloc] initWithBytes:buffer length:buflen encoding:NSUTF8StringEncoding]. buflen could be strlen(buffer) if buffer is a normal, NUL-terminated C string.