International Chars in UIAlertView on iOS - iphone

I'm having trouble displaying international chars in UIAlertView.
I'm retrieving strings in JSON format from this URL.
The returned format is ok and it contains the correct characters.
When I try to load it in my app in an UIAlertView I see this:
What is the right way to display Unicode characters from Spanish, Croatian, Chinese, etc?
Changing the default language in the settings did not solve the problem.

Without any code, it's quite difficult to point out where you're going wrong. The code below works, I can only assume you're doing something particularly fruity with the encoded data.
NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://kancelarijahatipovic.com/translate.php?from=eng&dest=hr&phrase=iron"]] returningResponse:nil error:nil];
NSString *string = [NSString stringWithUTF8String:[data bytes]];
SBJsonParser *parser = [[SBJsonParser alloc] init];
id returnVal = [parser objectWithString:string];
if( [returnVal isKindOfClass:[NSDictionary class]]) {
//build string
NSMutableString *alertString = [NSMutableString string];
if( [returnVal objectForKey:#"tuc"] != nil ) {
NSArray *tucs = [returnVal objectForKey:#"tuc"];
for( id tucObject in tucs ) {
if( [tucObject isKindOfClass:[NSDictionary class]] && [tucObject objectForKey:#"phrase"] != nil ) {
id phraseObject = [tucObject objectForKey:#"phrase"];
if( [phraseObject isKindOfClass:[NSDictionary class]] && [phraseObject objectForKey:#"text"] != nil ) {
[alertString appendFormat:#"%#\n", [phraseObject objectForKey:#"text"]];
}
}
}
}
if( alertString.length > 0 ) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"example" message:alertString delegate:nil cancelButtonTitle:#"okay" otherButtonTitles: nil];
[alertView show];
}
}
Edit: the SBJsonParser objectWithData: provides the same result as above.

Related

How to parse HTML sub tags in iPhone app?

I have HTML webpage with lot of images and live contents. I need to parse the data from the webpage(HTML) and show in the iPhone app. Am using the following code to parse the HTML content. But i don't know how to parse the sub tags in the tags?
{
NSURL *url = [NSURL URLWithString:#"http://www.samplewebpage.com/vd/t/1/830.html"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response : %#", responseString);
NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
NSMutableArray *divClassArray = [[NSMutableArray alloc] init];
//NSString *regexStr = #"<A HREF=\"([^>]*)\">";
// For image : 1. img src=\"([^>]*)\" 2. <img src=\"([^>]*)\">
// For getting Class div class
NSString *regularExpressString = #"div class=\"([^>]*)\"";
NSError *error;
NSInteger i =0;
while (i<[responseString length])
{
NSRegularExpression *testRegularExpress = [NSRegularExpression regularExpressionWithPattern:regularExpressString options:NSRegularExpressionCaseInsensitive error:&error];
if( testRegularExpress == nil )
{
NSLog( #"Error making regex: %#", error );
}
NSTextCheckingResult *textCheckingResult = [testRegularExpress firstMatchInString:responseString options:0 range:NSMakeRange(i, [responseString length]-i)];
NSRange range = [textCheckingResult rangeAtIndex:1];
if (range.location == 0)
{
break;
}
NSString *classNameString = [responseString substringWithRange:range];
NSLog(#"Div Class Name : %#", classNameString);
[divClassArray addObject:classNameString];
i= range.location;
//NSLog(#"Range.location : %i",range.location);
i=i+range.length;
}
NSLog(#"divClass Array : %#, Count : %d", divClassArray, [divClassArray count]);
}
Response:
<div class="phoneModelItems" style="width:30%;margin-right:4px;">Nokia Model</div>
I want to get the text Nokia Model from the class phoneModelItems. Can you please tell me how to retrieve the text 'Nokia Model'? Thanks in advance.
Here is my Regular Expression for your problem:
<div\sclass=\"phoneModelItems\".*?><a\shref.*?>(.*?)<\/a><\/div>
you can test it on Rubular

Arabic string in NSMutableArray or NSMutableDictionary

I have a problem when I add an arabic string to NSMutableArray or NSMutableDictionary.
Example:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"%#",data);
Output:
2012-01-18 21:55:05.646 aa[367:207] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
my problem exactly i save this data to sqlite [data objectForKey:#"name"] its saved \U0641\U0631\U0633\U0627\U0646 and when fetch data to to put it in UILabel or anything like it the text be \U0641\U0631\U0633\U0627\U0646
Any Help? Thank you :)
- (void)SaveMessage {
NSMutableDictionary *TableProperties = [[NSMutableDictionary alloc]init];
[TableProperties setObject:#"INSERT" forKey:#"Operation"];
[TableProperties setObject:#"savedmessages" forKey:#"tableName"];
NSString *string = [[NSString alloc]initWithFormat:#" %#",MessageBox.text];
[TableProperties setValue:string forKey:#"message"];
NSString *msgResult;
NSArray *result = [[DatabaseFunctions database] DataBaseOperation:TableProperties];
if ([[result objectAtIndex:0] isEqualToString:#"Done"])
msgResult = #"تم حفظ الرسالة بنجاح";
else
msgResult = #"لم تت العملية بنجاح حاول لاحقا";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"حفظ الرسالة"
message:msgResult
delegate:self
cancelButtonTitle:#"موافق"
otherButtonTitles:nil, nil ];
[alert show];
}
- (NSArray *)DataBaseOperation:(NSMutableDictionary *)TableProperties{
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *Operation = [TableProperties objectForKey:#"Operation"];
if ([Operation isEqualToString:#"SELECT" ]) {
NSString *tableColumns = [TableProperties objectForKey:#"tableColumns"];
NSString *tableName = [TableProperties objectForKey:#"tableName"];
NSString *tableWhere = [TableProperties objectForKey:#"tableWhere"];
NSString *tableOrder = [TableProperties objectForKey:#"tableOrder"];
NSString *tableLimit = [TableProperties objectForKey:#"tableLimit"];
NSString *Query;
if ([tableLimit isEqualToString:#"NO"]) {
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}else{
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %# LIMIT %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}
NSArray *FieldArray = [[TableProperties objectForKey:#"tableColumns"] componentsSeparatedByString:#","];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *Row = [[NSMutableDictionary alloc]init];
NSString *uniqueId = [[NSString alloc] initWithFormat:#"%i",sqlite3_column_int(statement, 0)];
[Row setObject:uniqueId forKey:#"uniqueId"];
for (int i = 1; i<[FieldArray count]; i++) {
NSString *column = [[NSString alloc] initWithUTF8String:(char *) sqlite3_column_text(statement, i)];
[Row setObject:column forKey:[FieldArray objectAtIndex:i]];
}
Objects *rowOfTable = [[Objects alloc] initSelectDataFromTables:Row];
Row = nil;
[retval addObject:rowOfTable];
}
sqlite3_finalize(statement);
}
}
else if([Operation isEqualToString:#"INSERT" ]) {
NSString *tableName = [TableProperties objectForKey:#"tableName"];
[TableProperties removeObjectForKey:#"Operation"];
[TableProperties removeObjectForKey:#"tableName"];
NSArray *Columns = [TableProperties allKeys];
NSArray *Values = [TableProperties allValues];
NSString *Query = [[NSString alloc] initWithFormat:#"INSERT INTO %# %# VALUES %#",tableName,Columns,Values];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK)
if (SQLITE_DONE!=sqlite3_step(statement)){
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}else{
NSLog(#"Data inserted Successfully");
[retval addObject:#"Done"];
}
else{
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}
sqlite3_finalize(statement);
}
return retval;
}
When you log an object using %#, NSLog sends the description message to the object and prints the resulting string.
An NSDictionary responds to the description message by encoding its keys and values in a "safe" format, escaping non-ASCII characters using \U#### codes.
If you pass the Arabic string to NSLog directly, it will just print the string without the escape codes:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"data = %#",data);
NSLog(#"string = %#", [data objectForKey:#"name"]);
Output:
2012-01-18 14:17:42.498 Animal[62723:f803] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
2012-01-18 14:17:42.500 Animal[62723:f803] فرسان
If you don't like the way NSDictionary responds to description, you will have to write your own method to format a dictionary as a string and use it to log your dictionary.
Update
I have looked at the source code you posted that talks to sqlite. The problem is that you are turning the values array ([TableProperties allValues]) into a string using the %# format specifier. This sends the description method to the NSArray, which returns a string. Just like NSDictionary, NSArray formats the description string in a "safe" format, escaping non-ASCII characters using \U#### codes.
You need to write your own method that takes an array and turns it into a string and does not escape special characters. (It needs to escape quotes though.)

Separating a string?

- (IBAction)doUpload:(id)sender {
NSMutableString *str = [[NSMutableString alloc] initWithString:#"Selected: "];
for(int i = 0; i < [appDelegate.notesArray count]; i++) {
// UPLOAD STRINGS HERE
if(selected[i]) {
[str appendFormat:#"%# ", [appDelegate.notesArray objectAtIndex:i]];
}
}
UploadView *uploadview = (UploadView *)self.view;
if(uploadview != nil) {
[m_owner uploadString:str];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Selected Values" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
// [self dismissModalViewControllerAnimated:YES];
}
}
In the above code, the str variable contains some values from the tableview cell. My tableview has multiple selection enabled, so str contains multiple values.
This code:
[m_owner uploadString:str];
is used for uploading to gdoc, but when str contains multiple values, it uploads all the values at the same time. I want to separate the values, and then upload them one by one.
How can I do this?
NSString *str = #"Hi ! I am iPhone Developer";
NSArray *myWords = [str componentsSeparatedByString:#"!"];
NSString *str1 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:0]];
NSString *str2 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:1]];
NSLog(#"%#",str1);
NSLog(#"%#",str2);
You will find in Log like this
Hi
I am iPhone Developer
If you just want to separate the components you can try using the componentsSeperatedByString: method. As a result you will be getting an array of objects which you can use to iterate for uploading.
[yourString componentsSeparatedByString:separatorString];
hope this helps.

How to pase a JSON array in iphone sdk?

I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/

how to compare a NSURLconnection http response data with a string value in iphone?

I want to do an activation module which will send a http request with a PIN number and then read the response. If the response is "OK", it opens up with a main menu. The problem is that I am receiving the response as "OK" but I am unable to compare it with a NSString #"OK". How to compare the http response with a string?
Here is my piece of code:
-(IBAction) submitPINAction:(id) sender
{
printf("inside submit btn");
mydata = [NSMutableData alloc];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://192.168.100.3/WWTF/activationApp.php?PIN=11111"]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if(connection)
{
mydata = [[NSMutableData data] retain];
}
else
{
//Handle error : Not received data
printf("No internet connection");
}
}
-(void)connection:(NSURLConnection *)theConnection
didReceiveData:(NSData *)incrementalData {
printf("data received");
if (mydata==nil) {
mydata =
[[NSMutableData alloc] initWithCapacity:2048];
}
[mydata appendData:incrementalData];
NSString *temp = [[NSString alloc] initWithData:mydata encoding:NSASCIIStringEncoding];
NSString *string1 = #"OK";
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([string1 isEqualToString:temp]){ // HERE IS THE PROBLEM, THE STRINGS ARE NOT GETTIN COMPARED
[prefs setBool:TRUE forKey: #"activationKey"];
// show the main menu
mainMenuController *mmC = [[mainMenuController alloc]initWithNibName:#"mainMenu" bundle:[NSBundle mainBundle]];
self.mmainMenuController = mmC;
[mmC release];
[self.view addSubview:[mmainMenuController view]];
}
else{
printf("in else");
[prefs setBool:FALSE forKey: #"activationKey"];
//show an alert
UIAlertView *alertActivationFail = [[UIAlertView alloc] initWithTitle:#"Activation Failed!" message:#"PIN is Incorrect" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertActivationFail show];
[alertActivationFail release];
}
}
I would use the following line, to see that the response is actually the OK string, cause it may contain white space or other characters.
NSLog(#"string1 = '%#' temp = '%#'", string1, temp);
put this line before the if statement like this...
NSString *string1 = #"OK";
NSLog(#"string1 = '%#' temp = '%#'", string1, temp);
if([string1 isEqualToString:temp]){ // HERE IS THE PROBLEM, THE STRINGS ARE NOT GETTIN COMPARED
If extra whitespace is the reason why the comparison is failing then you can trim whitespace from you string by using the following method:
+(NSString *)trim:(NSString *)value {
return [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
Another thing I would make sure is that you've received all the data before you check for the string. It looks like you do the string checking in didReceiveData, but it may make more sense to do the check in connectionDidFinishLoading after the data is complete.
Thank you Korros and danvin for helping me out.
The problem was indeed with whitespaces.
I trimmed the whitespaces as you said and it worked.
and Thanks stackoverflow.com . It is really a great forum.I find helpful ansers for all iPhone related topics, at the same time it also helps other platform as well i believe.