Converting array of xml elements to an array of floats? - objective-c

I have the following problem:
I am parsing a XML file, that contains a few "chas" elements. I save them in an array - arrayBegin. How to convert every object of the array to float ? I am a newbie, so I am really sorry for the dumb question. Thanks in advance! Here is my code:
NSString *dayToString = [NSString stringWithFormat:#"http://pik.bg/TV/bnt1/02.04.2013.xml"];
NSURL *url = [NSURL URLWithString:dayToString];
NSData *webData = [NSData dataWithContentsOfURL:url];
// every <chas> element from the xml file
NSString *xPathQueryBegin = #"//elem/chas";
TFHpple *parserBegin = [TFHpple hppleWithXMLData:webData];
NSArray *arrayBegin = [parserBegin searchWithXPathQuery:xPathQueryBegin];
NSLog (#"%d", [arrayBegin count]);

By this:
NSMutableArray *floatArray=[NSMutableArray new];
for(NSString *string in arrayBegin){
floatArray[floatArray.count]=#([string floatValue]);
}

Related

How to convert cv::Mat object into NSArray?

I write this conversion like this:
NSData *data = [NSData dataWithBytes:mat.data length:mat.elemSize() * mat.total()];
NSArray *array = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:data error:nil];
However I get array = nil. What's wrong with this conversion?
Answered by berak
Converting OpenCV Mat to array (possibly NSArray)

Objective-C Split a String and get last item

I have a string like so:
NSString *path = #"\\fake\aaa\bbb\ccc\ddd\eee.pdf";
and I split the string into an array like so:
NSArray *array = [path componentsSeparatedByString:#"\"];
Now there are two things I need here.
I need a string with everything except eee.pdf
I need the last item in the array as a string (eee.pdf)
How would I do this?
Just for fun, there is a little-known way to get an NSURL with its benefit from a windows file path
NSString *path = #"\\\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSURL *url = CFBridgingRelease(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLWindowsPathStyle, false));
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
Finally you have to convert parentDirectory back to windows path style (backslashes).
But if you mean POSIX paths used in OS X, it's much easier
NSString *path = #"/fake/aaa/bbb/ccc/ddd/eee.pdf";
NSURL *url = [NSURL fileURLWithPath:path];
NSString *fileName = url.lastPathComponent;
NSString *parentDirectory = url.URLByDeletingLastPathComponent.path;
I think you're trying to get the filepath and filename from a full path. There are better ways of doing that. But since you simply asked for the question, here's my answer. Please note that this is not the best approach. In addition, you have to escape the backslashes by using a preceding backslash.
NSString *path = #"\\fake\\aaa\\bbb\\ccc\\ddd\\eee.pdf";
NSArray *array = [path componentsSeparatedByString:#"\\"];
NSMutableArray *removedArray = [[NSMutableArray alloc] init];
for(int i=0; i< array.count -1; i++){
[removedArray addObject:[array objectAtIndex:i]];
}
NSString *joinedString =[removedArray componentsJoinedByString:#"\\"];
NSString *fileName = [array lastObject];
NSLog(#"Path: %#", joinedString);
NSLog(#"Filename: %#", fileName);
For the last element use the lastObject property of the NSArray.
For a string without the last element use subarrayWithRange: using array.count-1 for the NSRange length.
Then join the remaining array with componentsJoinedByString:.
NSString *fileName = [array lastObject];
NSArray *newArray = [array subarrayWithRange:NSMakeRange(0, array.count-1)];
NSString *directoryPath = [newArray componentsJoinedByString:#"\\"];

yahoo weather api parsing

How can I parse the wind spped for the following JSON that I have received from the link
http://weather.yahooapis.com/forecastjson?w=2502265. I am getting a garbage value from it but getting the rest of the values correctly. Can anybody let me know how can I get the wind speed out of it?
{"units":{"temperature":"F","speed":"mph","distance":"mi","pressure":"in"},"location":{"location_id":"USCA1116","city":"Sunnyvale","state_abbreviation":"CA","country_abbreviation":"US","elevation":82,"latitude":37.39,"longitude":-122.03},"wind":{"speed":0,"direction":"CALM"},"atmosphere":{"humidity":"86","visibility":"10","pressure":"30.21","rising":"falling"},"url":"http:\/\/weather.yahoo.com\/forecast\/USCA1116.html","logo":"http:\/\/l.yimg.com\/a\/i\/us\/nt\/ma\/ma_nws-we_1.gif","astronomy":{"sunrise":"06:27","sunset":"18:11"},"condition":{"text":"Fair","code":"33","image":"http:\/\/l.yimg.com\/a\/i\/us\/we\/52\/33.gif","temperature":49},"forecast":[{"day":"Today","condition":"PM Showers","high_temperature":"64","low_temperature":"47"},{"day":"Tomorrow","condition":"Partly Cloudy","high_temperature":"62","low_temperature":"45"}]}
NSString *linkForWoeid = [NSString stringWithFormat:#"http://where.yahooapis.com/geocode?location=%#,%#&flags=J&gflags=R&appid=zHgnBS4m",latitude,longitude];
NSURL *woeid = [NSURL URLWithString:linkForWoeid];
NSData *WoeidData = [NSData dataWithContentsOfURL:woeid];
if (WoeidData != NULL)
{
NSError *woeiderr = nil;
//NSLog(#"linkForWoeid:%#woeid:%#woeidData:%#",linkForWoeid,woeid,WoeidData);
NSDictionary *response1=[NSJSONSerialization JSONObjectWithData:WoeidData options:NSJSONReadingMutableContainers error:&woeiderr];
NSDictionary *woeidDict = [[[[response1 objectForKey:#"ResultSet"]objectForKey:#"Results"]objectAtIndex:0]objectForKey:#"woeid"];
NSString *address=[NSString stringWithFormat:#"http://weather.yahooapis.com/forecastjson?w=%#",woeidDict];
NSURL *url=[NSURL URLWithString:address];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *eqw=nil;
if (data != NULL)
{
NSDictionary *response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&eqw];
//NSLog(#"response:%#",response);
NSString *highTempDict = [[[response objectForKey:#"forecast"]objectAtIndex:0] objectForKey:#"high_temperature"];
NSString *temp = [highTempDict stringByAppendingFormat:#" 'F"];
NSString *windSpeed = [[response objectForKey:#"wind"] objectForKey:#"speed"];
NSLog(#"wind :%#",windSpeed);
if (windSpeed == 0)
{
NSLog(#"insideif");
windSpeed = #"0";
}
NSString *imageView = [[response objectForKey:#"condition"]objectForKey:#"image" ];
Hi Rasi Please use NSNumber instead of NSString here
NSNumber *windSpeed = [[response objectForKey:#"wind"] objectForKey:#"speed"];
As in JSON it's coming as integer value (without quotes) so it is not a NSString but NSNumber
And you can get it's string value as [windSpeed stringValue];

convert base64 decoded NSData to NSString

I'm trying to encode and decode base64 data. but while decoding the base64 data, it returns bunch of hex values, but i couldn't display or printout using NSlog to the original readable strings. The below code couldn't print anything, just empty.
Can anyone help ? thanks
>
>
NSString* msgEncoded = [[NSString alloc] initWithFormat:#"Q1NNKE1DTC9TTUEgUkNWL2FkbWluQHNldGVjcy5jb20gT1JHLyBUVkIvNDNkYzNlMzQwYWQ3Yzkp:"];
NSData* decoded = [[NSData alloc] initWithData:[self decodeBase64WithString:msgEncoded]];
NSString* plainString = [[NSString alloc]initWithData:decoded encoding:NSUTF8StringEncoding];
NSLog(#"\n Decoded string: %# \n", plainString );
There is a built in function in NSData
[data base64Encoding];
[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
If you are still having issues, try out this library: https://github.com/l4u/NSData-Base64
use it like so:
#import "NSData+Base64.h"
NSData *someData //load your data from a file, url or photo as needed
NSData *file = [NSData dataWithContentsOfFile:#"mytextfile.txt"];
NSData *photo = UIImageJPEGRepresentation(self.photo.image,1);
//encode it
NSString *base64string = [photo base64EncodedString];
NSString *base64file = [file base64EncodedString];
//decode it
NSData *back = [NSData dataFromBase64String:base64string];
Try Google's GTMStringEncoding class. You'll need GTMDefines.h too.
GTMStringEncoding *coder = [GTMStringEncoding rfc4648Base64StringEncoding];
NSString *encodedBase64 = [coder encodeString:#"Mary had a little lamb"];
// will contain the original text
NSString *decodedText = [coder decodeString:encodedBase64];
To encode NSData* to NSString* and back to NSData*, use the encode: + decode: methods instead of encodeString: + decodeString:.
As a bonus you get a lot of additional useful encodings, such as the url-safe variant of Base64.

Parsed TouchXML XML file crashes when reading NSString

I'm able to successfully parse the contents of a XML file using TouchXML, but when I try to read an individual NSString, from the NSMutableArray that stores the parsed content, the iPhone app crashes.
My NSLog shows me that the file has been parse as it should, giving this output:
(
{
href = "mms://a19349.l412964549958.c41245496.f.lm.akamaistream.net/D/194359/4125596/v0001/reflector:49944";
},
{
href = "mms://a4322.l4129624350471.c414645296.a.lm.akamaistream.net/D/473432/4129566/v0001/reflector:546441";
} )
Here is the code I'm using to do the parsing:
NSMutableArray *res = [[NSMutableArray alloc] init];
.... Parsing happens here ....
Then I try to retrieve the string from the NSMutableArray, using this code (and the app crashes when trying to read this line of code, posted below NSMutableString *string1 = [NSMutableString stringWithString:url];
NSString *url = [[NSString alloc] init];
url = [res objectAtIndex:0];
NSMutableString *string1 = [NSMutableString stringWithString:url];
[string1 deleteCharactersInRange: [string1 rangeOfString: #"href = "]];
[string1 deleteCharactersInRange: [string1 rangeOfString: #";"]];
NSLog(#"Clean URL: %#", string1);
Please, how can I solve this problem? Thank you!
TouchXML returns you an array of NSDictionaries. In order to extract string you need to take value from this NSDictionary:
NSString *url = [[res objectAtIndex:0] objectForKey:#"href"];