NSXML parsing error when used with NSData - iphone

I have a simple XML file containing a subset list of products. When I load the file from the iOS App bundle and send it through the parser with: initWithNSURL, with an NSURL pointing to the local file it parses correctly.
However if I download the same file via an NSURLConnection and pass it to the parser with initWithData, the parsing fails. I can confirm the data is being downloaded correctly because if I perform NSString *temp = [NSString stringWithUTF8String:[downloadedData bytes]]; the outputted string is correct.
I have a guy feeling it's sometime to do with encoding somewhere along the line, any thoughts?

My friend do the parser job,
NSString* xmlData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
xmlData should look like
abc
and my friend just analyze the string,and it's work
and I used libxml2 to parse xml with
xmlTextReaderPtr reader = xmlReaderForMemory([data bytes], [data length], NULL, NULL, (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
const xmlChar *name, *value;
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
NSString *Name = [NSString stringWithCString:(const char*)name encoding:NSUTF8StringEncoding];
value = xmlTextReaderConstValue(reader);
if (value == NULL)
value = BAD_CAST "\n";
NSString *Value = [NSString stringWithCString:(const char*)value encoding:NSUTF8StringEncoding];
NSLog("%d %d %# %d %#",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
Name,
xmlTextReaderIsEmptyElement(reader),
Value);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
}
and result is correct too

Related

NSString unichar from int

I have an int value which I obtained from the character 爸, which is 29240. I can convert this number to hex, but I have no clue how to write the chinese character out in an NSString with only the int 29240.
Basically, what I did was:
NSString * s = #"爸";
int a = [s characterAtIndex:0];
NSLog(#"%d", a);
What it gave as output was 29240.
However, I don't know how to create an NSString that just contains 爸 from only the int 29240.
I converted 29240 into binary which gave me 7238, but I can't seem to create a method which allows me to input any integer and NSLog the corresponding character.
I can hard code it in, so that I have
char cString[] = "\u7238";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
But I'm not sure how to do it with any int.
Thanks to anyone who can help me!
To create a string from one (or more) Unicode characters use initWithCharacters:
unichar c = 29240;
NSString *string = [[NSString alloc] initWithCharacters:&c length:1];
NSString uses UTF-16 characters internally, so
this works for all characters in the "Basic Multilingual Plane", i.e. all characters up to U+FFFF. The following code works for arbitrary characters:
uint32_t ch = 0x1F60E;
ch = OSSwapHostToLittleInt32(ch); // To make it byte-order safe
NSString *s1 = [[NSString alloc] initWithBytes:&ch length:4 encoding:NSUTF32LittleEndianStringEncoding];
NSLog(#"%#", s1);
// Output: 😎
Try out this code snippet to get you started in the right direction:
NSString *s = #"0123456789";
for (int i = 0; i < [s length]; i++) {
NSLog(#"Value: %d", [s characterAtIndex:i]);
}
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];

BLOB data is not displaying in UITextView

hello,
I am stucked at the last part of it, Please help me on it.
In this there are three views, first one, for list of books( in UITableView), second is chapters(in UITableView) and last one is for content,which is in text format (in UITextView).
Upto second view it is working very fine.Problem is, when i select any chapters in second view, text view in third view displays nothing.But in output it displays the sequence of numbers.
code to fetch data from database and display into UITextView.
NSMutableString *mStr = [NSMutableString stringWithFormat:#"select content from content where name = \"%#\" and chapterno = %#",chapName,chapNo];
const char *sql =(char *)[mStr UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_prepare(dbContent, sql, -1, &sqlStmt, NULL)!=SQLITE_OK)
{
NSLog(#"prob with prepare statement: %s",sqlite3_errmsg(dbContent));
}
else
{
while (sqlite3_step(sqlStmt)==SQLITE_ROW) {
len = sqlite3_column_bytes(sqlStmt, 0);
NSData *cData = [[NSData alloc]initWithBytes:sqlite3_column_blob(sqlStmt, 0) length:len];
NSString *nstr = [NSString stringWithUTF8String:[cData bytes]];
myTextView.text = nstr;
}
In above chapName is coming from first view and chapNo is selected row in second view.
content table looks like:
id bookid name chapterno content
1 1 abc 1 BLOB(size:4217)
2 1 abc 2 BLOB(size:3193)
3 1 abc 3 BLOB(size:3501)
O/p comes in a long sequence of numbers like this..
<0d0a3120 496e2074 68652062 6567696e 6e696e67 20476f64 20637265 61746564 20746865 20686561 76656e20 616e6420 74686520 65617274 682e0d0a...>
Here, text content i need to display in text view. What i'm missing here?
I think the problem is NSData to NSString conversion. If your Sqlite strings are not null-terminated converting with following line should help.
NSString* nStr = [[NSString alloc] initWithData:cData
encoding:NSUTF8StringEncoding];
NSMutableArray *ar=[[NSMutableArray alloc] init];
NSString *strQuery=[NSString stringWithFormat:#"select content from content where name = \"%#\" and chapterno = %#",chapName,chapNo];
const char *sql =[mStr UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_open([self.dbPath UTF8String], &database)==SQLITE_OK)
{
if(sqlite3_prepare_v2(database, query, -1, &compiledStmt, NULL)==SQLITE_OK){
while (sqlite3_step(sqlStmt)==SQLITE_ROW) {
len = sqlite3_column_bytes(sqlStmt, 0);
NSData *cData = [[NSData alloc]initWithBytes:sqlite3_column_blob(sqlStmt, 0) length:len];
NSString *nstr = [NSString stringWithUTF8String:[cData bytes]];
myTextView.text = nstr;
[ar addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 1) length:sqlite3_column_bytes(compiledStmt, 1)],#"data1",
[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStmt, 2)],#"data2",nil]];
}
else {
NSLog(#"Invalid query");
}
NSArray *arToReturn=([ar count]>;0)?[NSArray arrayWithArray:ar]:nil;
ar=nil;
return arToReturn;
}
Please implement following code and let me inform any problem and query genrated.
I have found a simplest alternate way for it.
Since, I am taking book name(from first table view) and chapter number(from second table view) from the database and passing it to detail view page.
Lets say here, my books names are maths, physics, geography..and chapters are in numerals (1,2,3...).Only thing is needed to keep the file name as
[booknamechpatername.txt]
#book name- Maths
chapter1-->> maths1.txt
chapter2-->> maths2.txt
...
#book name - Physics
chapter1 -->> physics12.txt
...
geography21.txt
...so on..
and drag it to iphone resource or any folder you want.
Now, Store that file into string and display into UITextView.
-(void)loadFile{
NSError *error;
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *docDir = [dirPath objectAtIndex:0];
if (!docDir) {
NSLog(#"Doc dir not found");
}
NSString *str = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:#"%#%#",chapName,chapNo] ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:str encoding:NSUTF8StringEncoding error:&error];
myTextView.text = content;
}
and call it in viewDidLoad
[self loadFile];
Otherwise, this link https://github.com/jblough/bible-ios would help, if you want to go through database only.

How to search a word from the .txt file that has been included in the project in xcode

I have included a .txt file in my project and i have to find a keyword from that file by entering the keyword in the search bar. Help me with the piece of code for searching the keyword that is present in the file.
Try that
//Get the contents of the file
NSString *contentString = [NSString stringWithContentOfFile:<i>path/to/your/file.txt</i> encoding:<i>textEncoding<i> error:<i>&error</i>];
if (!error) {
NSRange range = [contentString rangeOfString:<i>yourKeyword</i>];
if (theRange.location != NSNotFound)
//do whatever you want
}
NB : this will work as long as your text file is not "too big". If you have to work with bigger files, take a look at NSInputStream to only parse chunks of the file
Try this:
-(void)searchWord:(NSString *)wordToBeSearched{
NSString* path = [[NSBundle mainBundle] pathForResource:#"wordFile"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *delimiter = #"\n";
NSArray *items = [content componentsSeparatedByString:delimiter];
NSString *character = #" ";
BOOL isContain = NO;
for (NSString *wordToBeSearched in items) {
isContain = ([string rangeOfString:wordToBeSearched].location != NSNotFound);
}
return isContain;
}
You can go here for more details

Converting NSString, data type expression, to actual NSData

NSString *string1 = #"<616263>";
I want to make this into NSData *data1 = <616263>;
so that when I
NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", string2);
Result: abc
would come out
p.s.
<616263>, this is data expression of #"abc"
The trick is converting 616263 to abc. Since you are starting with the ASCII representation of the character codes, you need to convert your NSString to an array of bytes (or your original data source to an array instead of saving it as an NSString in the first place).
NSString *string1 = #"616263";
// Make sure that buffer is big enough!
char sourceChars[7];
[string1 getCString:sourceChars maxLength:7 encoding:NSUTF8StringEncoding];
char destBuffer[3];
char charBuffer[3];
// Loop through sourceChars and convert the ASCII character groups to char's
// NOTE: I assume that these are always two character groupings per your example!
for (int index = 0; index < [string1 length]; index = index + 2) {
// Copy the next two digits into charBuffer
strncpy(charBuffer, &sourceChars[index], 2);
charBuffer[2] = '\0';
// convert charBuffer (ie 61) from hex to decimal
destBuffer[index / 2] = strtol(charBuffer, NULL, 16);
}
// destBuffer is properly formatted: init data1 with it.
NSData *data1 = [NSData dataWithBytes:destBuffer length:[string1 length]/2];
// Test
NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", string2); // Prints abc

Converting hex string to hex data

I currently have an NSString containing hex values. I need to convert this NSString object into an NSData object, without changing its contents at all.
I use this code to "parse" the debug output of an NSData object (what you get in the console if you just NSLog an NSData object) back into NSData:
-(NSData*) bytesFromHexString:(NSString *)aString;
{
NSString *theString = [[aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:nil];
NSMutableData* data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= theString.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [theString substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
if ([scanner scanHexInt:&intValue])
[data appendBytes:&intValue length:1];
}
return data;
}
It's not my most robust code, but it does the job of parsing [nsdata_object description].