Decoding the scanned barcode value to int value - ios

When I scan the barcode and I get some value if it is Equal=2 then I need to display with == and if it is Equal=3 then I need to display with = and if the value is 4 then invalid.
But Scanned Barcode are of integer value -- when decode using NSASCII it is displaying only till value 127 after that it is showing invalid results. Eg: if my Barcode value = 9699 the result value=jem then my added result value=jem= actualstring value=%åasc value id only showing 37
Here is my code:
- (void) readerView:(ZBarReaderView *)view didReadSymbols:(ZBarSymbolSet *)syms fromImage:(UIImage *)img
{
// do something useful with results -- cool thing is that you get access to the image too
for (ZBarSymbol *symbol in syms) {
[resultsBox setText:symbol.data];
if ([resultsBox.text length] == 2) {
addedresult.text = [resultsBox.text stringByAppendingString:#"=="];
} else if ([resultsBox.text length] == 3) {
addedresult.text = [resultsBox.text stringByAppendingString:#"="];
} if ([resultsBox.text length] >= 4) {
addedresult.text = #"Invalid";
}
[Base64 initialize];
NSString *myString = [[NSString alloc]initWithString:addedresult.text];
NSData * data = [Base64 decode:myString];
NSString * actualString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",actualString);
labeltext.text= actualString;
int asc = [actualString characterAtIndex:0];
label.text = [NSString stringWithFormat:#"%d", asc];
[actualString release];
break;
}
}

Since someone revived this question's comments, i'll revive this entire post.
You shouldn't go through NSData to create an NSString from something you already have, and you're probably losing something along the way. Go directly to NSString using stringWithFormat. Also, ASCII will come back and byte you later, if you have a choice, use UTF8.
NSString *actualStringUTF8 = [NSString stringWithFormat:#"%#",[addedresult.text urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSString *actualStringASCII = [NSString stringWithFormat:#"%#",[addedresult.text urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",actualStringUTF8);
NSLog(#"%c",[actualStringUTF8 UTF8String]); //This is a const char*
Secondly, I looked into the SDK and it says symbol.data is already an NSString*. Depending on what you want, you may not need to do anything. If you do end up needing to change encoding, make sure you understand why you need to (one good reason is "the rest of the application uses NS****StringEncoding").
Also make sure you compare strings the correct "Objective-C" way:
[actualString isEqualToString: testString];
NOT actualString == testString;

Related

Display Unicode String as Emoji

I currently receive emojis in a payload in the following format:
\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F
which represents "🚣‍♀️"
However, if I try to display this, it only shows the string above (escaped with 1 less ), not the emoji e.g.
NSString *emoji = payload[#"emoji"];
NSLog(#"%#", emoji) then displays as \U0001F6A3\U0000200D\U00002640\U0000FE0F
It's as if the unicode escape it not being recognised. How can I get the string above to show as an emoji?
Please assume that the format the data is received in from the server cannot be changed.
UPDATE
I found another way to do it, but I think the answer by Albert posted below is better. I am only posting this for completeness and reference:
NSArray *emojiArray = [unicodeString componentsSeparatedByString:#"\\U"];
NSString *transformedString = #"";
for (NSInteger i = 0; i < [emojiArray count]; i++) {
NSString *code = emojiArray[i];
if ([code length] == 0) continue;
NSScanner *hexScan = [NSScanner scannerWithString:code];
unsigned int hexNum;
[hexScan scanHexInt:&hexNum];
UTF32Char inputChar = hexNum;
NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
transformedString = [transformedString stringByAppendingString:res];
}
Remove the excess backslash then convert with a reverse string transform stringByApplyingTransform. The transform must use key "Any-Hex" for emojis.
NSString *payloadString = #"\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F";
NSString *unescapedPayloadString = [payloadString stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"];
NSString *transformedString = [unescapedPayloadString stringByApplyingTransform:#"Any-Hex" reverse:YES];
NSLog(#"%#", transformedString);//logs "🚣‍♀️"
I investigated this, and it seems you may not be receiving what you say you are receiving. If you see \U0001F6A3\U0000200D\U00002640\U0000FE0F in your NSLog, chances are you are actually receiving \\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F at your end instead. I tried using a variable
NSString *toDecode = #"\U0001F6A3\U0000200D\U00002640\U0000FE0F";
self.tv.text = toDecode;
And in textview it is displaying the emoji fine.
So you got to fix that first and then it will display well.

base 64 encoding objective-c

I am trying to convert copied images on the iOS pasteboard from a string to an image. 90% of the time this works under the scheme i have with URL's. However 1/10 times the image is not a url but is of what seems to be a base 64 encoding. The string looks like this.
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEBIPExMVFRAVEBAQEBYQFRUVDxAQFREWFhUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGhAQGy0lICUtLS0wLS8tLS0tLS0tLS8tLS0tLS0tLS0tLS0tLi0tLS0tLSstLS4tLS0tLSstLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAADAAECBAUGB//EAEIQAAEDAwIDBQYDBgQEBwAAAAEAAhEDBCExUQUSQRMiYXGBBhQykaGxQsHwBxVSYnPRIzNygpKz4fEXJFNkorLS/8QAGgEAAwEBAQEAAAAAAAAAAAAAAQIDAAQFBv/EAC8RAAICAQIEAgoDAQEAAAAAAAABAhEDEiEEEzFRQbEFIjJhcZHB0eHwFIGh8UL/2gAMAwEAAhEDEQA/AO2YjNWPSvlYbfBfOaGe22majSpgrMF6FIXo3W0sTSafMlzLPF2N1IXQ3QoHLL8pwVQFyN1MV0KNy2XQU4KqdunFdYXQy4CnBVUVlIVkBXBloOUw9U+3TisgLoZeD1MPVEVlMVlhXAvCopCoqIrKQrLCOBd7RN2iqdql2q1g0Fo1FA1FX7VN2iwdAcvUC9BL0xesMohS5RLkPmTF6I2knKaVDnTc6waCSlKFzJ+ZENE5SJQ+ZKVjUOUNykSoErUMgZSTlJChzl6Vg5WGWRWy0BTwq81m0oxvdHJjauW1AT8oQ5jDRhG2cnFu9bvZhSFILcxmtGIy3cjNpOWuKITiihrBqRkcjku8tnsExt0HP3B5iMgPcpio7ZaJt0vd0uv3B1ozu1dsnbVdstEWymLUIORubEzxVKftitAWYU22KXUDmwKNOoSrlK2qO0atawsAMxlabWwuvh+DnmWpukcuTiUnUUcxUtao/CfRVajnDUFdkQql5aNcNE+b0fOC1Rdiw4r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jEYESJ2KIxxIEuzMGMwYznCE74onEBM+qBIwAc9UwrAXLIIkjAB8jGh8UAMEidNW4yJzpOdVbZTBP4YiTHVRdTAyP9o6BU1MTSiDHAHIE41AaI6ERqoEDEHIxHT0RXsxOpQ+zODtr6rIxB7z/1P3TsqxJ18B1xrk/qVGqNY8spNGMjER67phSTnnq3p4SPTpr9VB0SHRH0MqT3QBgdNNVF1XyGNtfNMrQrpgvefA/VJOSTnRJPqiJpZWbUPTRSaJ6qsyqjU3KggcslM6niEmuUi5AZEOzCcUgkHJuZAIixGt7ca9eiC10qzSJBSz2Q0N2SFHMozaQj7IRcpseSueSZ0JoTaIB+6J2KEapBTseRlI0x00TeTGY0WW6mSVarV5KEHQrQjROUkwYpiM9EANVprxMnZBqJ0nYsmq2K7GGVYbRG+ZTsaEZjQjIEF3AimQiMCMGBHp0xEqbZSrKhONVetHQJKE5jSnpjELTVxFW0izUIgmdUmkxk4Q+QwEziQIKikUbCEAmVCpS8QfNQFQAKDHyU4hJzcQMeScvIAkIbjAU2PkaogGbWORCTavh1RGviEqhRABc/qAk+v03+QRJGqjduDtBAj6ogBjIlQGnRRnEJgcIgGNUJkPkKSNi0UaZRw9OkrkSbUZqSSDGQxdCTjhOkggsjTRqZJTpIS6Gh1LDW4SmEklzHUJplQrVOiZJGK3BJ7AAniUklayaREsTCmkkinsK1uPypuqSSUeg0wFHtCkktQWx+dPTqwUkln0FvoaDKuNFGq+eiSS5ki7BBkqYpDVJJGwA30ZQjSKSSMWLJEhTKlyHdJJNYtCcxMWpJJrBRXe3qq5fASSRQrBGoU6SS1go//9k=
Now I use the following code to recognize its base64 based off a post I found.
- (BOOL)isBase64Data :(NSString *)input{
input=[[input componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:#""];
if ([input length] % 4 == 0) {
static NSCharacterSet *invertedBase64CharacterSet = nil;
if (invertedBase64CharacterSet == nil) {
invertedBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]invertedSet];
}
return [input rangeOfCharacterFromSet:invertedBase64CharacterSet options:NSLiteralSearch].location == NSNotFound;
}
return NO;
}
However it always returns false. Does this string I show need some trimming in some way? I find the length of the string to be 8391 therefore modulo 4==0 is never invoked.
/9j/4AAQSkZJ is a typical beginning of JPEG data, converted to hex as FFD8FFE00010+JFIF. If you want to convert it to an image, you need to point the converter to the point AFTER the data:image/jpeg;base64, text.
I think you can do something like this:
NSData *base64 = [yourData subdataWithRange:NSMakeRange(24, yourData.length-24)];
NSData *imgData = [[NSData alloc] initWithBase64EncodedData:base64 options:0];
UIImage *img = [UIImage imageWithData:imgData];
I might be wrong with the exact implementation but this is the general idea...

Getting write request value from NSArray with Core Bluetooth

I have a method here:
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
NSLog(#"PERIPHERAL: peripheralManager:%# didReceiveWriteRequests:%#", peripheral, requests);
NSString * result = [[requests valueForKey:#"description"] componentsJoinedByString:#""];
_label.text = result;
}
I receive the write request in an NSArray. Right now I am just converting the full array into a string and outputting the string into a text box. To make sure everything is set up correctly. It indeed is working, but I do not want the full array listed but just the value alone stored in a NSString.
I want this in a string:
Test
Not this:
CBATTRequest: 0x1702240 Central = , Characteristic = , Offset = 0, Value = test
This should be easy to accomplish and I am possibly just brain dead from a long day. How is this supposed to be done?
You need to consider that requests is an array of CBATTRequests, which have a value property containing an NSData object representing the data being written.
If you want one string representing all of the values, you need to iterate over requests and convert each of these NSData values to NSString and concatenate them. If I'm understanding your question correctly, this should be what you're looking for.
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests {
NSMutableString *output = [[NSMutableString alloc] init];
for (CBATTRequest *request in requests) {
NSString *stringValue = [[NSString alloc] initWithData:[request value] encoding:NSUTF8StringEncoding];
if (stringValue) {
[output appendString:stringValue];
}
}
_label.text = output.copy;
}
As a note, updating to Xcode 7 would help make this more clear, since the requests parameter of -peripheralManager:didReceiveWriteRequests: has updated to use Objective-C generics, and now has the type NSArray<CBATTRequest *> *.

NSArray element to NSString

I have application where I receive from socket message like: "\r\nIDLE|03/17/2013 19:48\n". I convert this message into UTF8 string with code:
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
then I try to separate command and time from this string:
NSArray *nums = [command componentsSeparatedByString:[NSString stringWithFormat:#"%c", (char)13]];
NSLog(#"First separate = %#", nums);
if ([nums count] == 3)
{
NSArray *nums1 = [[nums objectAtIndex:1] componentsSeparatedByString:#"|"];
NSLog(#"second separate = %#", nums1);
if ([nums1 count] == 2)
{
NSString* strState = [(NSString *)[nums1 objectAtIndex:0] description];
NSLog(#"State = %#", strState);
...
}
}
in the log I see next:
First separate = (
"IDLE|03/17/2013 19:48",
"\n"
second separate = (
"IDLE",
"03/17/2013 19:48"
State = I
After second separating in the 0 elements I have text IDLE, but when I try to get this text I strState variable, I see only first character of this text.
Can anybody help me get full command of this element?
Thank you.
UPDATE1
As I say previously I get from socket message like:"\r\nIDLE|03/17/2013 19:48\n"
I'm sure that the server send me this message.
in the Socket read callback I'm use next code for reading this message:
int result = CFReadStreamRead(_inputStream, (UInt8*)[data mutableBytes], length);
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Here app read 50 bytes and this is right for this message? you can see my debugger at this point in the next picture:
but in the newStr member I see only \r.
then I send try separate this message with code I wrote above.
When I try separate message logger show me all message instead of \r:
Thank you
Have you considered using sscanf()?
char command[COMMAND_SIZE_LIMIT];
char date[DATE_SIZE_LIMIT];
char time[TIME_SIZE_LIMIT];
sscanf (input, "\r\n%[^|]%*[|]%s%s\n", command, date, time);
(Note: Above is example code; you've got a security issue if the scanned string has oversized command or datetime substrings.)
# test
ebg#ebg$ ./foo
Input: '
IDLE|03/17/2013 19:48
'
Command: 'IDLE'
Date: '03/17/2013'
Time: '19:48'
It is easy to convert NSString <==> C string.
There is a fairly straightforward way to accomplish what you want using the -[NSString stringByTrimmingCharactersInSet:] method. Passing the whitespace and newline character set allows you to trim the leading and trailing whitespace and newlines from your string, and then you only need to do a single call to componentsSeparatedByString:.
NSString *raw = #"\r\nIDLE|03/17/2013 19:48\n";
NSString *trimmedString = [raw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray *components = [trimmedString componentsSeparatedByString:#"|"];
NSString *command = components[0];
NSString *time = components[1];
NSLog(#"command = %#, time = %#",command,time);
This code yields the following output:
command = IDLE, time = 03/17/2013 19:48

How to convert NData populated with hex values to NSString

I have a NSdata object that is populated with a bunch of information thats formated in hex.. I am trying to convert it into its proper string representation but am struggling to have any success.
One thing I have tried is to simply put it into a NSString and then NSLog it with a special character identifier thingy.. forgot the word (%02x), However to do this I am encoding it to NSUTF16.. which i dont want to do.. I mearly want to see exactly whats the data I am getting looks like as a NSString.
The reason I am doing this is because I am having some issues with my encoding later on in my code and im not sure if its because the data I am receiving is incorrect or me stuffing it up at some point when I am handling it.
Any help would be appreciated.
You can get a string representation of your NSData like so:
NSData *data = (your data)
NSString *string = [NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];
Does that answer your question?
Maybe I haven't understood, but something like this:
NSData *yourData;
NSLog(#"%#", [yourData description]);
doesn't fit your need?
Give this a try -
-(NSString*)hexToString:(NSData*)data{
NSString *hexString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%d", decimalValue];
}
return string;
}

Resources