I am sending URLRequest as mentioned below.
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
And I am getting #"23.0984 USD" in balanceString
Then I would like to display it on uilabel.tex= 23.09 USD Please help me
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
float amount = [balanceString floatValue]; // This will return 23.0984 as a float
NSString *formattedAmount = [NSString stringWithFormat:#"%01.2f USD", amount];
Then something like this should work:
NSString * inp = #"29.2994 USD";
// Initialize a scanner to process the input
NSScanner * scanner = [NSScanner scannerWithString:inp];
// Pull out a floating point value
float v;
[scanner scanFloat:&v];
NSCharacterSet * ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
// scan through the whitespace after the float
[scanner scanCharactersFromSet:ws intoString:nil];
NSString * currency;
[scanner scanUpToCharactersFromSet:ws intoString:¤cy];
// write out value:
uilabel.text= [NSString stringWithFormat:#"%.2f %#",v,currency];
There might be easier ways.. But this should work..
NSString *originalString = #"23.0984 USD";
NSString *numberString = [originalString stringByReplacingOccurrencesOfString:#" USD"
withString:#""];
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:#"%.2f",number];
NSLog(#"ChangedString : %# USD",changedString);
EDIT: This answer is already accepted. But I think a better method to get number from string is to search for spaces rather than replacing hardcoded string #" USD".
NSString *originalString = #"23.0984 USD";
NSString *numberString = nil;
NSArray *parts = [originalString componentsSeparatedByString:#" "]; //space
if(parts && [parts lenght]){
numberString = [parts objectAtIndex:0];
}
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:#"%.2f",number];
NSLog(#"ChangedString : %# USD",changedString);
Related
I have string
this string is encoded with euc-kr..
I try this code
NSString *str = MjAxObPitbUgx9C7/bq4yKPAzrfCKLnov/LFzcH2xbTAzCkguPDB/SCw+LDt
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:str options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:kCFStringEncodingEUC_KR];
but result is null..
what is wrong..? and I try
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:kCFStringEncodingDOSKorean];
and
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:kCFStringEncodingMacKorean];
but result is same..
encoding:kCFStringEncodingMacKorean's result is not korean.;;;;;
Here is a working solution:
Starting with:
NSString *str = #"MjAxObPitbUgx9C7/bq4yKPAzrfCKLnov/LFzcH2xbTAzCkguPDB/SCw+LDt";
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:str options:0];
What you missed is that you can't really use kCFStringEncodingEUC_KR which is a CFStringEncodings with initWithData:encoding: with expects a NSStringEncoding.
You can use CFStringConvertEncodingToNSStringEncoding() to convert it:
NSString *result = [[NSString alloc] initWithData:decodedData encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingEUC_KR)];
NSLog(#"result: %#", result);
Output:
$>result: 2019년도 학생보호인력(배움터지킴이) 모집 공고
If you want to use "natively" the kCFStringEncodingEUC_KR, and all the CFDataRef, CFStringRef, and use the bridge then to convert CFStringRef to NSString:
CFStringRef ref = CFStringCreateWithBytes(nil, [decodedData bytes], [decodedData length], kCFStringEncodingEUC_KR, false);
NSString *result = (__bridge NSString *)ref;
NSLog(#"result: %#", result);
Output:
$>result: 2019년도 학생보호인력(배움터지킴이) 모집 공고
You might need to do some changes, I'm not really familiar with CFStringCreateWithBytes(), check the documentation.
I am trying this.
-(NSString *)convertEmojiIntoUnicode:(NSString *)emojiStr{
NSData *data = [emojiStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return goodValue;
}
For Decoding
-(NSString *)convertUnicodeToEmoji:(NSString *)unicodeStr{
NSString *newString = unicodeStr;
NSData *data1 = [newString dataUsingEncoding:NSUTF8StringEncoding];
NSString *goodValue1 = [[NSString alloc] initWithData:data1 encoding:NSNonLossyASCIIStringEncoding];
return goodValue1;
}
for characters like è is converting to \350 with above method but I am getting unicode for è- \u00E8 from android and website.
I can decode \350 and \u00E8 both with above decode method(convertUnicodeToEmoji) to è
Simply try out this solution :
NSString *myString = #"Here is conversion of char ë, é";
NSData *mData = [myString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *strResult = [[NSString alloc] initWithData:mData encoding:NSASCIIStringEncoding];
NSLog(#"Result: %#", strResult);
Here is Output :
Result: Here is conversion of char e, e
Hope it will work for you.
I'm trying to learn JSON with IOS since I'm a beginner in IOS devices, i tried this code so far
-(void)retriveData
{
NSURL *url = [NSURL URLWithString:#"http://localhost/testjson.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cities = [[NSMutableArray alloc] init];
for (int i=0; i<json.count; i++) {
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"CityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"CityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"CityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"Country"];
Country *myCity = [[Country alloc] initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry];
[cities addObject:myCity];
}
}
Anyone can show me now how i can print the data? this is the json file
[{"0":"1","id":"1","1":"Muscat","CityName":"Muscat","2":"Muscat","CityState":"Muscat","3":"25000","CityPopulation":"25000","4":"Oman","Country":"Oman"},{"0":"2","id":"2","1":"Bawsher","CityName":"Bawsher","2":"Muscat","CityState":"Muscat","3":"10000","CityPopulation":"10000","4":"Oman","Country":"Oman"},{"0":"3","id":"3","1":"AlMawalih","CityName":"AlMawalih","2":"Seeb","CityState":"Seeb","3":"5000","CityPopulation":"5000","4":"Oman","Country":"Oman"},{"0":"4","id":"4","1":"Oran","CityName":"Oran","2":"Oran","CityState":"Oran","3":"100000","CityPopulation":"100000","4":"Algeria","Country":"Algeria"},{"0":"5","id":"5","1":"Constantine","CityName":"Constantine","2":"Constantine","CityState":"Constantine","3":"150000","CityPopulation":"150000","4":"Algeria","Country":"Algeria"}]
Below is my very understandable and basic coding according to your question.It is helpful for you.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/testjson.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"The json output array is - %#",jsonArray);
for(int i=0;i>[jsonArray count];i++)
{
NSString *strZero = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"0"]];
NSLog(#"The zero is-%#",strZero);
NSString *strOne = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"1"]];
NSLog(#"The One is-%#",strOne);
NSString *strTwo = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"2"]];
NSLog(#"The Two is-%#",strTwo);
NSString *strThree = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"3"]];
NSLog(#"The three is-%#",strThree);
NSString *strFour = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"4"]];
NSLog(#"The four is-%#",strFour);
NSString *strID = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"id"]];
NSLog(#"The ID is-%#",strID);
NSString *strCityName = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityName"]];
NSLog(#"The CityName is-%#",strCityName);
NSString *strCityState = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityState"]];
NSLog(#"The CityState is-%#",strCityState);
NSString *strCityPopulation = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityPopulation"]];
NSLog(#"The CityPopulation is-%#",strCityPopulation);
NSString *strCountry = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"Country"]];
NSLog(#"The Country is-%#",strCountry);
}
By printing you mean show the data in the console ?
Did you try this ?
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", str);
I have to convert unicode char to NSString
the text i have to convert is doc.title = "hello 64 \U00bf world sample"
my code is:
UILabel *lblName=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 250, 88)];
const char *cString = [doc.title UTF8String];//where doc.title is above text
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
lblName.text= string;
NSLog(#"Title is = %# \n",doc.title);
lblName.font=[UIFont boldSystemFontOfSize:16];
lblName.numberOfLines=100;
lblName.backgroundColor=[UIColor clearColor];
lblName.textColor=[UIColor colorWithRed:2.0/255.0 green:104.0/255.0 blue:170.0/255.0 alpha:1.0];
[cell.contentView addSubview:lblName];
[lblName release];
where am i doing wrong?
Tried the link but could not get it right.
+(NSString *)getTextFromChar:(unichar)character
{
NSString *string = [NSString stringWithFormat:#"%C",character];
return string;
}
Pass your cString to this method
try this
char *cString[] = [doc.title UTF8String];//where doc.title is above text
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
lblName.text= string;
or simply call
-[NSString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES].
I erased the code between the lines, because it's nothing special, just adding a contact to an array. I think it has to do with the brackets. So hopefully someone has a good eye and can tell me, why its always adding a contact two times :)
if ([string rangeOfString:#"00"].location == NSNotFound) {
if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
} else if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(0, [str length] - 0)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(0, [str length] - 0)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
if ([string rangeOfString:#"+"].location == NSNotFound) {
if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
} else if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(3, [str length] - 3)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(3, [str length] - 3)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
if ([string rangeOfString:#"+"].location == NSNotFound) condition should start with else.
It should be as below:
else if ([string rangeOfString:#"+"].location == NSNotFound)
Also, before the second if line (mentioned below)
if ([string rangeOfString:#"+"].location == NSNotFound))
you should have closed '}' for first if.
If some of the omitted code is executing twice, it's because the construction of your strings is such that two of your if statements are both true for the same string. Examine your strings, post the one that is being added twice. Does one of them have a + and 00 in it? But your bracketing is fine.
UPDATE
I guess I would start hunting this down by adding NSLog() statements to each of the if/else blocks to see when each is called. If you have a remote web service, the error could be there as well. In fact, it might be -- your obj-c code looks ok to me. Track GET requests at the server and add logging to phpFile.php.