Despite many tries I have already done.. I am not getting to display correctly items from an NSArray into a UILabel..
When I NSLog the array the console returns me this:
2013-01-19 14:34:32.799 bloom[2766:c07] (
"0.877"
)
Which is the value I fetched from a website and parsed and etc..
The problem is that when I display it in a UILabel it shows me exactly the same thing and I need just the value without quotes to be displayed. Here's is how it is displaying:
Edit:
Here is my code:
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
for (NSDictionary *valuesDatum in _detailItem) {
NSDictionary *itemAtIndex = (NSDictionary *)_detailItem;
self.title = [itemAtIndex objectForKey:#"SYMBOL"];
NSString *strUrl = #"http://www.bloomberg.com/quote/";
NSString *ativo = [itemAtIndex objectForKey:#"SYMBOL"];
NSString *consulta = [strUrl stringByAppendingString:ativo];
NSURL *url = [NSURL URLWithString:consulta];
NSData *webData = [NSData dataWithContentsOfURL:url];
NSString *xPathQuery = #"//span[#class=' price'] | //span[#class=' trending_up up'] | //span[#class=' trending_up up']/span | //table[#class='snapshot_table']/tr/td";
TFHpple *parser = [TFHpple hppleWithData:webData isXML:NO];
NSArray *array = [parser searchWithXPathQuery:xPathQuery];
valores = [[NSMutableArray alloc]init];
for (TFHppleElement *element in array) {
[valores addObject:[[element firstChild] content]];
}
novosValores = [[NSMutableArray alloc]init];
for (NSString *valuesDatum in valores) {
NSString *removeNewLine = [[valuesDatum componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#" "];
NSString *removeSpace = [removeNewLine stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *removeSpaceOne = [removeSpace stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *trocaVirgulaPonto = [removeSpaceOne stringByReplacingOccurrencesOfString:#"," withString:#"."];
[novosValores addObject:trocaVirgulaPonto];
}
valoresFinais = [[NSMutableArray alloc]init];
for (NSString *valuesDatum in novosValores) {
NSArray *val = [valuesDatum componentsSeparatedByString:#" - "];
[valoresFinais addObject:val];
}
infos = [[NSMutableArray alloc]init];
for (NSArray *dados in valoresFinais) {
NSArray *arrayDados = [[NSArray alloc]initWithArray:dados];
for (NSString *teste in arrayDados) {
NSArray *arrayTeste = [teste componentsSeparatedByString:#","];
[infos addObject:arrayTeste];
}
}
NSLog(#"%#",[infos objectAtIndex:0]);
NSString *fff = [[NSString alloc] initWithFormat:#"%#", [infos objectAtIndex:0]];
[_detailDescriptionLabel setText:fff];
}
}
}
NEW EDIT:
I have this array:
2013-01-19 15:43:05.055 bloom[3564:c07] (
"7.730",
"0.020",
"0.26%",
"7.750",
"7.650-7.800",
"2.333.100",
"7.710",
"3.730-8.810",
"+4.04%"
)
All I need is a new array with the data from lines 5 and 8 separated by the "-".
So anyone has a light??
Thanks!!!
I solved this question with the help of Anoop. I changed a bit his code and finally my code is like this:
for (NSDictionary *valuesDatum in _detailItem) {
NSDictionary *itemAtIndex = (NSDictionary *)_detailItem;
self.title = [itemAtIndex objectForKey:#"SYMBOL"];
NSString *strUrl = #"http://www.bloomberg.com/quote/";
NSString *ativo = [itemAtIndex objectForKey:#"SYMBOL"];
NSString *consulta = [strUrl stringByAppendingString:ativo];
NSURL *url = [NSURL URLWithString:consulta];
NSData *webData = [NSData dataWithContentsOfURL:url];
NSString *xPathQuery = #"//span[#class=' price'] | //span[#class=' trending_up up'] | //span[#class=' trending_up up']/span | //table[#class='snapshot_table']/tr/td";
TFHpple *parser = [TFHpple hppleWithData:webData isXML:NO];
NSArray *array = [parser searchWithXPathQuery:xPathQuery];
valores = [[NSMutableArray alloc]init];
for (TFHppleElement *element in array) {
[valores addObject:[[element firstChild] content]];
}
novosValores = [[NSMutableArray alloc]init];
for (NSString *valuesDatum in valores) {
NSString *removeNewLine = [[valuesDatum componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#" "];
NSString *removeSpace = [removeNewLine stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *removeSpaceOne = [removeSpace stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *removeSpaceTwo = [removeSpaceOne stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *removeDash = [removeSpaceTwo stringByReplacingOccurrencesOfString:#" - " withString:#" "];
NSString *trocaVirgulaPonto = [removeDash stringByReplacingOccurrencesOfString:#"," withString:#"."];
[novosValores addObject:trocaVirgulaPonto];
}
NSString *fullString=[novosValores componentsJoinedByString:#"_"];
NSString *changeDash = [fullString stringByReplacingOccurrencesOfString:#"-" withString:#"_"];
finalArray=[changeDash componentsSeparatedByString:#"_"];
//NSLog(#"%#", finalArray);
}
NSString *str = [[NSString alloc]initWithFormat:#"%#",[finalArray objectAtIndex:10]];
[_detailDescriptionLabel setText:str];
Are you sure you make like this:
label.text = [array objectAtIndex:0];
instead of:
label.text = array;
(
"0.877"
)
The above is an array, and you are putting that array onto label.
You have to use someLabel.text=[thatArray objectAtIndex:0];
EDIT:
As per your requirement try this one: (not compiler checked)
NSString *fullString=[array componentsJoinedByString:#"+"];
NSArray *brokenString=[fullString componentsSeparatedByString:#"-"];
NSString *mainString=brokenString[1];
NSArray *finalArray=[mainString componentsSepartedByString:#"+"];
Related
How to get the date and title and description alone from this parsing result:
title = "Inter-views 29/03/2017 random description here (its in arabic);
title = " \U0627\U062e\U0628\U0627\U0631 \U0627\U0644\U0635\U0628\U0627\U062d 14/04/2017";
That's the parsing from same api but different (didSelectRowAtIndexPath).
I'm currently using this code but as I notified the parsing is different. So I cannot use static logic.
Code:
NSString *myString = [item objectForKey:#"title"];
NSMutableArray *myArray = [[NSMutableArray alloc]
initWithArray:[myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" "]]];
NSString *Category = #"";
if(myArray.count>=1){
Category = [myArray objectAtIndex:0];
[myArray removeObjectAtIndex:0];
}
NSString *Date = #"";
if(myArray.count>=1) {
Date = [myArray objectAtIndex:0];
[myArray removeObjectAtIndex:0];
}
cell.dateLabel.text = [[NSString alloc] initWithFormat:#"%#", [Utils dateTransform:[Date stringByReplacingOccurrencesOfString:#" " withString:#""] FromFormat:#"dd-MM-yyyy" ToFormat:#"dd-MMMM-yyyy"]];
NSString *Title = #"";
for (NSString *word in myArray) {
Title = [Title stringByAppendingString:word];
Title = [Title stringByAppendingString:#" "];
}
cell.titleAndDescLabel.text =[NSString stringWithFormat:#"%# %#", Category,Title];
Your have to use for loop to get value
for (NSInteger i=0; i<[[jsonObject objectForKey:#"yourMainKey"]count]; i++)
{
NSString *strname =[[[jsonObject objectForKey:#"yourMainKey"]objectAtIndex:i]objectForKey:#"date"];
NSLog(#"strname==%#, strname);
NSString *str title =[[[jsonObject objectForKey:#"yourMainKey"]objectAtIndex:i]objectForKey:#"title"];
NSLog(#"strtitle ==%#, strtitle);
NSString *str description =[[[jsonObject objectForKey:#"yourMainKey"]objectAtIndex:i]objectForKey:#"description"];
NSLog(#"description ==%#, description);
}
I can't save my new data to plist file for some reason. This is code I have been using for saving data:
-(void)saveData:(NSMutableDictionary *)dictionaryData toFile:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:filename];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
[data addObject:dictionaryData];
[data writeToFile:filename atomically:YES];
}
this is code I used to copy file from bundle to app directory in case if it is not there :
-(NSMutableArray *)loadFromFile:(NSString *)filename {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:filename];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if(![fileMgr fileExistsAtPath:path]) {
NSArray *fileArray = [filename componentsSeparatedByString:#"."];
NSString *name = [fileArray objectAtIndex:0];
NSString *ext = [fileArray objectAtIndex:1];
NSString *bundle = [[NSBundle mainBundle] pathForResource:name ofType:ext];
[fileMgr copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
return data;
}
For some reason I can't save new data to plist file. When I try to add new NSMutableDictionary object to my plist file (with saveData:toFile: method) and than reload my array variable with the plist file data - new object is not there. Am I doing something wrong?
this is how I load plist file :
#property (nonatomic, strong) NSMutableArray *modules;
#property (nonatomic, strong) NSMutableDictionary *module;
- (void)viewDidLoad {
[super viewDidLoad];
self.modules = [self loadFromFile:#"ModulesList.plist"];
self.module = [self.modules objectAtIndex:0];
for (int i = 0; i < self.modules.count; i++ ) {
NSLog(#"Modules array from plist file, module at index %i : %#",i, [self.modules objectAtIndex:i]);
}
than for testing purpose I have this code to add new module object:
- (IBAction)leftButton:(id)sender {
NSString *mytitle = [[NSString alloc] initWithFormat:#"my title"];
NSString *myauthor = [[NSString alloc] initWithFormat:#"my author2"];
NSUInteger myean = 22023423;
NSString *mytitle2 = [[NSString alloc] initWithFormat:#"my title 2"];
NSString *myauthor2 = [[NSString alloc] initWithFormat:#"my author2"];
NSUInteger myean2 = 29032432;
NSString *mytitle3 = [[NSString alloc] initWithFormat:#"my title 3"];
NSString *myauthor3 = [[NSString alloc] initWithFormat:#"my author 3"];
NSUInteger myean3 = 21023423;
NSMutableDictionary *mybook = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mybook2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mybook3 = [[NSMutableDictionary alloc] init];
[mybook setObject:mytitle forKey:#"title"];
[mybook setObject:myauthor forKey:#"author"];
[mybook setObject:[NSNumber numberWithInteger:myean] forKey:#"ean"];
[mybook2 setObject:mytitle2 forKey:#"title"];
[mybook2 setObject:myauthor2 forKey:#"author"];
[mybook2 setObject:[NSNumber numberWithInteger:myean2] forKey:#"ean"];
[mybook3 setObject:mytitle3 forKey:#"title"];
[mybook3 setObject:myauthor3 forKey:#"author"];
[mybook3 setObject:[NSNumber numberWithInteger:myean3] forKey:#"ean"];
NSMutableArray *mybooks = [[NSMutableArray alloc] init];
[mybooks addObject:mybook];
[mybooks addObject:mybook2];
[mybooks addObject:mybook3];
[self.module setObject:mybooks forKey:#"books"];
[self.modules addObject:self.module];
for (int i = 0; i < self.modules.count; i++ ) {
NSLog(#"Modules array after add operation, module at index: %i: %#",i, [self.modules objectAtIndex:i]);
}
[self saveData:self.module toFile:#"ModulesList.plist"];
}
than when I will reload my self.modules array from plist with button action, my new data is not there:
- (IBAction)reload:(id)sender {
self.modules = [self loadFromFile:#"ModulesList.plist"];
for (int i = 0; i < self.modules.count; i++ ) {
NSLog(#"RELOAD: Modules array from plist file, module at index %i : %#",i,[self.modules objectAtIndex:i]);
}
}
this is screenshot of my plist file : http://dl.dropbox.com/u/49076351/Screen%20Shot%202013-02-27%20at%2016.27.45.png
I'm trying to do a list of lists... but when I use [listaCidades count] ...i'm getting throwing exception (sorry for long question but I mean that all this method is relevant for the question)
-(void) preencherCidades {
for (int iCnt = 0; iCnt < [listaEstados count]; iCnt++) {
NSString *estado = [listaEstados objectAtIndex:iCnt];
NSArray *listaNomeCidades = nil;
NSMutableArray *_listaCidades = [[NSMutableArray alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:estado ofType:#"txt"];
NSString *file = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
listaNomeCidades = [[file componentsSeparatedByString:#"\n"]retain];
for (int iCnt2 = 0; iCnt2 < [listaNomeCidades count]; iCnt2++) {
NSArray *listaNomesPrefeitos = nil;
NSArray *listaPartidosPrefeitos = nil;
NSArray *listaVereadores = nil;
NSString *pathNomePrefeitos = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"prefeito-nome-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *fileNomePrefeitos = [NSString stringWithContentsOfFile:pathNomePrefeitos encoding:NSUTF8StringEncoding error:NULL];
listaNomesPrefeitos = [[fileNomePrefeitos componentsSeparatedByString:#"\n"]retain];
NSString *pathPartidoPrefeitos = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"prefeito-partido-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *filePartidoPrefeitos = [NSString stringWithContentsOfFile:pathPartidoPrefeitos encoding:NSUTF8StringEncoding error:NULL];
listaPartidosPrefeitos = [[filePartidoPrefeitos componentsSeparatedByString:#"\n"]retain];
NSString *pathVereadores = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"vereadores-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *fileVereadores = [NSString stringWithContentsOfFile:pathVereadores encoding:NSUTF8StringEncoding error:NULL];
listaVereadores = [[fileVereadores componentsSeparatedByString:#"\n"]retain];
Prefeito *prefeito = nil;
if([listaNomesPrefeitos count] > 0 && [listaPartidosPrefeitos count]>0)
prefeito = [[Prefeito alloc]initWithNome:[listaNomesPrefeitos objectAtIndex:0] partido:[listaPartidosPrefeitos objectAtIndex:0] id:iCnt2];
Cidade *cidade = [[Cidade alloc]initWithNome:[listaNomeCidades objectAtIndex:iCnt2] prefeito:prefeito listaVereadores:listaVereadores id:iCnt2];
[_listaCidades addObject:cidade];
}
[listaCidades addObject:_listaCidades];
}
}
By looking at your answer [Cidade isEqualToString:]:unrecognized selector to instance 0x1cec00. I came to know that that is the only point where string is expected but you are returning Object.
Its good that you solve the issue. Happy Coding.
I solved this with
NSMutableArray *listaCidades2 = (NSMutableArray *)[listaCidades objectAtIndex:indiceEstado];
Cidade *cidade = (Cidade *)[listaCidades2 objectAtIndex:row];
return cidade.nome;
instead of:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSMutableArray *listaCidades2 = (NSMutableArray *)[listaCidades objectAtIndex:indiceEstado];
return [listaCidades2 objectAtIndex:row];
}
In my app a user can create UITextFields. to each field a tag is added, so that the tags correspond to the cases: 1, 2, 3, 4, ... then I add everything in a NSDictionary, and a json representation:
-(IBAction)buttonDropBoxuploadPressed:(id)sender{
//screenshot
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSString *filename = [NSString stringWithFormat:#"By: %# ",
[formatter stringFromDate:[NSDate date]]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%#", filename] ];
//[data writeToFile:path atomically:YES];
//NSString *destDir = #"/sandbox/";
// [[self restClient] uploadFile:filename toPath:destDir
// withParentRev:nil fromPath:path];
// [[self restClient] loadMetadata:#"/sandbox/"];
//JSON
NSString *object;
NSString *object2;
NSString *object3;
NSString *object4;
NSString *object5;
NSString *object6;
NSString *object7;
NSString *object8;
NSString *object9;
NSString *object10;
NSString *object11;
NSString *object12;
NSString *object13;
NSString *object14;
NSString *object15;
for (UITextField *text in messagename) {
int touchedtag = text.tag;
NSUInteger tagCount = touchedtag;
switch (tagCount) {
case 1:
object = [NSString stringWithFormat:#"%#", text.text];
break;
case 2:
object2 = [NSString stringWithFormat:#"%#", text.text];
break;
case 3:
object3 = [NSString stringWithFormat:#"%#", text.text];
break;
case 4:
object4 = [NSString stringWithFormat:#" %#", text.text];
break;
case 5:
object5 = [NSString stringWithFormat:#"%#", text.text];
break;
case 6:
object6 = [NSString stringWithFormat:#"%#", text.text];
break;
case 7:
object7 = [NSString stringWithFormat:#"%#", text.text];
break;
case 8:
object8 = [NSString stringWithFormat:#"%#", text.text];
break;
case 9:
object9 = [NSString stringWithFormat:#"%#", text.text];
break;
case 10:
object10 = [NSString stringWithFormat:#"%#", text.text];
break;
case 11:
object11 = [NSString stringWithFormat:#"%#", text.text];
break;
case 12:
object12 = [NSString stringWithFormat:#"%#", text.text];
break;
case 13:
object13 = [NSString stringWithFormat:#"%#", text.text];
break;
case 14:
object14 = [NSString stringWithFormat:#"%#", text.text];
break;
case 15:
object15 = [NSString stringWithFormat:#"%#", text.text];
break;
default :
break;
}
}
//arrays
NSString * objects[] = { object, object2, object3, object4, object5, object6, object7, object8, object9, object10, object11, object12, object13, object14, object15};
NSMutableArray *textnameobject = [[NSMutableArray alloc] initWithCapacity:b];
textnameobject = [NSMutableArray arrayWithObjects:objects count:b];
NSMutableArray *textnamekeys = [[NSMutableArray alloc] initWithCapacity:b];
NSString * textnumber[] = {#"title", #"title", #"title",#"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title", #"title"};
textnamekeys = [NSMutableArray arrayWithObjects:textnumber count:b];
//arrays
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObject: textnameobject forKey:textnamekeys];
/*
NSArray *objects2 = [NSArray arrayWithObjects:jsonDictionary, nil];
NSArray *keys2 = [NSArray arrayWithObjects:allkeys, nil];
NSDictionary *mainDict = [NSDictionary dictionaryWithObjects:objects2 forKeys:keys2];
*/
NSString* jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[jsonData writeToFile:path atomically:YES];
NSString *destDir = #"/sandbox/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:path];
[[self restClient] loadMetadata:#"/sandbox/"];
//JSON
}
When I press the button I get the following error:
JSONRepresentation failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"JSON object key must be string\" UserInfo=0x2e8370 {NSLocalizedDescription=JSON object key must be string}"
)
and consequentially a dropbox error. this worked on my previous app and the code is exactly the same. the json library is added correctly. I can't understand!! Please help!
Your code, rewritten.
- (IBAction)buttonDropBoxUploadPressed: (id)sender
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"yyyy_MM_dd"];
NSString *filename = [NSString stringWithFormat: #"By: %# ", [formatter stringFromDate: [NSDate date]]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: filename];
NSMutableDictionary *titles = [NSMutableDictionary dictionary];
for (UITextField *textField in messagename)
{
[titles setObject: textField.text forKey: #"title"];
// as you can see, here you're replacing the value # at key "title" with a new object on every pass
}
NSString *jsonString = [titles JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[jsonData writeToFile: path atomically: YES];
NSString *destDir = #"/sandbox/";
[[self restClient] uploadFile: filename toPath: destDir withParentRev: nil fromPath: path];
[[self restClient] loadMetadata: #"/sandbox/"];
}
However, regarding my comment, you're not actually serializing your text fields' text into anything usable. At the end of this, at best, you'll have something that looks like this:
{
"title": "My Text Field Value"
}
Though I'm also relatively certain that one or more of your text fields' text is nil, which is causing your JSON problem.
I just want to parse this JSON string in Objective-C using the SBJSON framework, and retrieve the three units of data:
{"x":"197","y":"191","text":"this is a string"}
How can this be done?
NSString * jsonString = #"{\"x\":\"197\",\"y\":\"191\",\"text\":\"this is a string\"}";
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:jsonString];
NSLog(#"x is %#",[dictionary objectForKey:#"x"]);
[jsonParser release];
Here's an example:
NSString *jsonText = #"...";
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *dict = [parser objectWithString:jsonText];
for (NSString *key in [#"x y text" componentsSeparatedByString:#" "]) {
NSLog(#"%# => %#", key, [dict objectForKey]);
}
Here's something similar for SBJson4Parser:
id parser = [SBJson4Parser parserWithBlock:^(id v, BOOL *stop) {
for (NSString *key in [#"x y text" componentsSeparatedByString:#" "]) {
NSLog(#"%# => %#", key, [v objectForKey]);
}
}
allowMultiRoot:NO
unwrapRootArray:NO
errorHandler:^(NSError *err) {
// handle error here
}];
NSString *jsonText = #"...";
[parser parse: [jsonText UTF8String]];