Access NSArray from dictionary - ios

I have a chat application. When I send push notification from the server, it sends me a NSArray value which I use it to forward user profile with NSNumber.
I printed push notification response with alertview and I added response picture. You can see the response of push notification.
I talked about "customDictionary" key. I want to access this '6297' value and after I want to convert to NSNumber.
Here is my code:
#property (nonatomic, copy) NSNumber *userID;
NSArray *array = [[[userInfo valueForKey:#"aps"] valueForKey:#"customDictionary"]array];
NSString *myArrayString = [array description];
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
format.numberStyle = NSNumberFormatterDecimalStyle;
self.userID = [format numberFromString:myArrayString];
userID is returning null. Is anybody can help me ? Thank you.

I think that the value of key 'customDictionary' is string, try this
NSString *unformattedString = [[userInfo valueForKey:#"aps"] valueForKey:#"customDictionary"];
NSCharacterSet *specialCharSet = [NSCharacterSet characterSetWithCharactersInString:#"[]"];
NSString *newString = [unformattedString stringByTrimmingCharactersInSet:specialCharSet];
NSLog(#"newString : %#",newString);

See your key "aps" give you a dictionary which actually doesn't contain the "customDictionary" key, its outside of your "aps" dictionary. Try the code given below. Good luck!!
NSArray *array = [[userInfo valueForKey:#"customDictionary"] array];
NSString *myArrayString = [array description];
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
format.numberStyle = NSNumberFormatterDecimalStyle;
self.userID = [format numberFromString:myArrayString];

Related

Corebluetooth NSMutableArray with characteristic values

Using the setNotify=YES property I want to create an array populated with the converted 'characteristic.value' values from the below code (Xcode7.2). So far I've only got a null array, all the same values, or only one value at a time
I've implemented
#property (strong, nonatomic) NSMutableArray *voltageArray; //didn't work so
I deleted and tried the following...
The method that I tried to use it in was didUpdateCharacteristic,
if (characteristic.isNotifying)
{
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value
encoding:NSUTF8StringEncoding];
NSNumber *number = [NSNumber numberWithUnsignedShort:stringFromData];
number = #([number floatValue] *5/2034);
NSLog(#"Characteristic Value: %#", _voltageArray);
}
I also tried the following in the didUpdateValueMethod, along with countless other things,
_voltageArray=[[NSMutableArray alloc] init];
[self.voltageArray addObject:number];
NSLog(#"Array: %#", _voltageArray);
The best I've gotten is all the same value or all null. How do I get these unsigned voltage values into an array?
Updated Solution
#property (strong, nonatomic) NSMutableArray *voltageArray;
-(void)peripheral: didUpdateValueForCharacteristic: error:{
if (characteristic.isNotifying)
{
if(!self.voltageArray){//Checks if voltageArray has been initialised
self.voltageArray = [[NSMutableArray alloc] init];//If not, initialise the array
}
// generate characteristic value
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
unsigned short baseValue = (unsigned short)stringFromData;
NSNumber *number = [NSNumber numberWithUnsignedShort:baseValue];
number = #([number floatValue] *5/2034);
NSLog(#"Characteristic Value: %#", number);
// give potential recording
self.voltageLabel.text = [NSString stringWithFormat:#"%#",number];
// datasource points y-axis
[_voltageArray addObject:number];
NSLog(#"Array: %#", _voltageArray);
There are a couple of errors that may be causing your issue.
First:
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value
encoding:NSUTF8StringEncoding];
NSNumber *number = [NSNumber numberWithUnsignedShort:stringFromData];
number = #([number floatValue] *5/2034);
The first method requires a unsigned short type as an input, but you are passing a NSString. You could do this instead:
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value
encoding:NSUTF8StringEncoding];
unsigned short baseValue = (unsigned short)stringFromData.intValue;
float convertedValue = (float)baseValue *5.0/2034.0; //5.0/2034.0 -> so it typecasts the result value as a float, not int
NSNumber *number = [NSNumber numberWithFloat: convertedValue];
[self.voltageArray addObject:number];
Second, it seems that you are initialising your array every time the didUpdateValueForCharacteristic gets called. Try this instead:
-(void)peripheral: didUpdateValueForCharacteristic: error:{
if (characteristic.isNotifying)
{
if(!self.voltageArray){//Checks if voltageArray has been initialised
self.voltageArray = [[NSMutableArray alloc] init];//If not, initialise the array
}
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value
encoding:NSUTF8StringEncoding];
unsigned short baseValue = (unsigned short)stringFromData.intValue;
float convertedValue = (float)baseValue *5.0/2034.0;
NSNumber *number = [NSNumber numberWithFloat: convertedValue];
[self.voltageArray addObject:number];
}
}
Hope this helps.

How to convert an NSString to an NSArray?

I have an NSString, that when I NSLog, it looks like this:
(
Music,
Music,
"Ao Dai Fashion Show"
)
I would like to convert this to an NSArray, where array[0] = Music, array[1] = Music, and array[2] = Ao Dai Fashion Show.
I have tried to first remove the () using:
NSString *jsonString = [str stringByReplacingOccurrencesOfString:#"()" withString:#""];
However, I receive an unrecognized selector sent to instance.
How can I achieve this?
Thanks
This is the original array:
NSArray *oriArray = [dictionary objectForKey:someKey];
NSLog:
(
{
"end_time" = "21:00";
"english_event" = Music;
"english_performer" = "DJ Happee From Channel 93.3";
"start_time" = "20:00";
},
{
"end_time" = "21:00";
"english_event" = Music;
"english_performer" = "Adam Cease";
"start_time" = "20:00";
},
{
"end_time" = "21:00";
"english_event" = "Ao Dai Fashion Show";
"english_performer" = "";
"start_time" = "20:00";
}
)
Here is the code to get the new NSArray containing contents Music, Music, "Ao Dai Fashion":
NSArray *newArry = [oriArray valueForKey:#"english_event"];
However, the newArry is giving me an error when I try to access its index.
I don't think that what you're logging is actually an NSString. Please check its type because it seems like it's already an instance of NSArray. Therefore you should already be able to do what you want.
-(void)parse:(NSDictionary*)dictionary{
NSArray *oriArray = [dictionary objectForKey:someKey];
NSMutableArray *arrray=[[NSMutableArray alloc] init];
for (NSDictionary *dic in oriArray)
{
[arrray addObject:[dic objectForKey:#"english_event"]];
}
}
use this it may help you....
Sorry I din't have the reputation to comment, I just thought of asking this, did you try-
NSArray *myArray = [stringOi componentsSeparatedByString:#","];
(*where stringOi is your str)
I tried with the following sample and this works, please do try yours.
NSString *stringOi=[NSString stringWithFormat:#"(
Music,
Music,
"Ao Dai Fashion Show"
)"];
NSLog(#"%#",stringOi);
NSString *jsonString = [stringOi stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *jsonStringFinal = [jsonString stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSLog(#"%#", jsonStringFinal);
NSArray *myArray = [jsonStringFinal componentsSeparatedByString:#","];
NSArray *myArray1 = [myArray objectAtIndex:0];
NSLog(#"%#",myArray1);
NSArray *myArray2 = [myArray objectAtIndex:1];
NSLog(#"%#",myArray2);
NSArray *myArray3 = [myArray objectAtIndex:2];
NSLog(#"%#",myArray3);
Alternatively instead of oriArray you can get the values in a dictionary dict and then,
NSArray *myArray1 = [dict objectForKey:#"english_event"];
NSString *Music= [myArray1 objectAtIndex:0];
Hope for the best..!
Two things:
NSArray *myArray = [myDictionary objectForKey:#"Valid Key"] does not mean that myArray is actually an Array. It just means it's a pointer to an object that you've cast as an NSArray.
You can convert any NSArray or NSDictionary to a string using [myDictionaryOrArray description].
If you don't care about taking extra steps and know that when you log out the array you get what you want/are expecting, then you can definitely get your string into an array. For example:
NSString *myString = [#[Music, Music, "Ao Dai Fashion Show"] description];
NSMutableArray *stringAsArray = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:#","]];
// this loop removes the white space before and after each word in the array
for (int i = 0; i < stringAsArray.count; i++) {
stringAsArray[i] = [stringAsArray[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
If you need more specific code for the longer sample you gave, I'll be happy to update my answer.
(
Music,
Music,
"Ao Dai Fashion Show"
)
this is an array not a string.
This array holds three strings in each indexes , Music, Music, Ao Dai Fashion Show

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

How to get the data from a row in an NSArray using only part of the row to search

Lets say i have an array filled with several rows
dates = [NSArray arrayWithObjects:#"2012-05-01||Blue", #"2012-05-02||Red", #"2012-05-03||Green", #"2012-05-04||Orange", #"2012-05-05||Yellow", #"2012-05-06||Purple", #"2012-05-07||Silver", nil];
and then I have a date to search by 2012-05-01
How do i search for an object by only part of it without doing a big for( loop because this array will theoretically hold a few thousand cells.
EDIT:
if necessary how do i load the data into an NSDictionary? (i've never used them)
I know i can get the data like so
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
}
NSMutableDictionary *colorsAndDates = [[NSMutableDictionary alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
for(NSString *row in dates) {
NSString *dateString = [[row componentsSeparatedByString:#"||"] objectAtIndex:0];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *color = [[row componentsSeparatedByString:#"||"] objectAtIndex:1];
[colorsAndDates setObject:color forKey:date];
}
If I am correct, this will format it into an NSDictionary, and then I can grab the color using:
NSString *dateToFind = #"2012-05-01";
NSDate *date = [dateFormatter dateFromString:dateToFind];
NSString *theColor = [colorsAndDates objectForKey:date];
Knowing this, I will have to go back and make it all revolve around NSDictionary instead of the strings they're in.
There's a couple of things you can do other than looping through the array:
1) Use a sorted array. Even if you need to keep the data in the initial order, you can make a sorted copy of it. Then you can do a binary search (if there are n items, check the n/2 item, if it's less than your date and repeat the process with only the data from n/2 to n, or if it's greater, then repeat with the data from 0 to n/2. Sort once, find many.
2) Create a dictionary on the fly using the data. You can use the the 10 character prefix of the data as the key. You'll have to maintain the dictionary along with the array, so this may not be practicable if you have a lot of changes. Create dictionary once, find many. (Note: despite the answers you've gotten, a dictionary may not be the best solution, particularly if you don't have unique keys (i.e. more than one record with the same date).
3) Forget the arrays and store your data in sqlite, and write a sql statement to get it. Most useful if you have a whole lot of data. You can use sqlite to build a primary key if you have duplicate dates in your data.
Creating a dictionary:
NSDictionary *dateDictionary = #{
#"2012-05-01" : #"Blue",
#"2012-05-02" : #"Red",
#"2012-05-03" : #"Green",
#"2012-05-04" : #"Orange",
#"2012-05-05" : #"Yellow",
#"2012-05-06" : #"Purple",
#"2012-05-07" : #"Silver"
};
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];
Using the example you gave (looping through the array to create a dictionary):
NSMutableDictionary *dateDictionary = [NSMutableDictionary dictionary];
for(NSString *row in dates) {
NSString *date = [[row componentsSeperatedByString:#"||"] objectAtIndex:0];
NSString *color = [[row componentsSeperatedByString:#"||"] objectAtIndex:1];
dateDictionary[date] = color;
}
NSString *date = #"2012-05-01";
NSString *dateColor = dateDictionary[date];

IOS: How to read specific data in one list of XML

When I use NSXMLParser to parse XML in iPhone app, I know how to do it in the scenario like this:
> <title>L3178 : Freiensteinau Richtung Grebenhain</title> // From XML
But, if I want to extract data from a list, e.x. I want to get the lat and lon from <>id>, how should I deal with that?
<>id>
http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00
<>/id>
It is very strange if I use instead of <>id>, it will disappear. So, I have to use this ugly notation.
Thank you in advance!
Create a method which extracts parameters from urlString
- (NSDictionary *)paramsFromURLString:(NSString *)urlString
{
NSRange range = [urlString rangeOfString:#"?"];
NSString *subString = [urlString substringFromIndex:range.location+range.length];
NSArray *components = [subString componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
for (NSString *string in components) {
NSRange subRange = [string rangeOfString:#"="];
NSString *key = [string substringToIndex:subRange.location];
NSString *value = [string substringFromIndex:subRange.location+subRange.length];
[params setObject:value forKey:key];
}
return params;
}
From the params find the lat and lon
NSString *urlString = #"http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00";
NSDictionary *params = [self paramsFromURLString:urlString];
NSString *latitude = params[#"lat"];
NSString *longitude = params[#"lon"];

Resources