I have this url: http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false
And this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSMutableDictionary *theDictionary = [responseString JSONValue];
NSLog(#"%#", theDictionary);
[responseString release];
if (theDictionary != nil)
{
NSArray *routesArray = [theDictionary objectForKey:#"routes"];
NSDictionary *firstRoute = [routesArray objectAtIndex:0];
NSArray *legsArray = [firstRoute objectForKey:#"legs"];
NSDictionary *firstLeg = [legsArray objectAtIndex:0];
steps = [firstLeg objectForKey:#"steps"];
}
[tableView reloadData];
}
I want to display every single #"html_instructions" on a uitableview.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.steps count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cachedCell"];
if (cell == nil)
cell = [[[UITableViewCell alloc]
initWithFrame:CGRectZero reuseIdentifier:#"cachedCell"] autorelease];
return cell;
}
What's missing in my code??? Should be some little detail... any help would be GREAT!
I would do it like this:
Create url request with your url
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://maps.google.com.br/maps/api/directions/json?origin=porto+alegre&destination=novo+hamburgo&sensor=false"]];
then create NSData structure, that holds response to the request and I converted it to string
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
After that, you load JSON into Dictionary, then to move one level down, pass it to another dictionary (result 1)
NSError *error=nil;
result = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
result1 = [result objectForKey:#"routes"];
result2 = [result1 objectForKey:#"legs"];
Then move it into NSMutableArray
jsonMutArray= [result2 objectForKey:#"steps"];
From there, you just put label into your custom cell attach it as a IBOutlet, synthetize and do in cellForRowAtIndexPath method
cell.yourLabel.text = [jsonMutArray objectForKey:#"html_instructions"];
However, keep in mind, that I'm just begginer, so this might not be the most effective way of doing it :) Good Luck!
Don't you need to be doing something like this in your CellForRowAtIndexPath ?
NSString *cellValue = **WHATEVER VALUE YOU WANT TO PUT IN**;
cell.textLabel.text = cellValue;
return cell;
I don't see you adding your data to the cell.
Related
I've typed some text in uitextview and also I've select some text and make it bold.After that I'm going to save this data into my application.Now,When I'm going to fetch that data then it will not displaying same as I've saved.
Its not save bold font.
Below is the code :
pragma mark - btnActions
-(IBAction)btnActions:(UIButton *)sender
{
[self addOrRemoveFontTraitWithName:#"Bold" andValue:UIFontDescriptorTraitBold];
}
pragma mark - Private method implementation
-(void)addOrRemoveFontTraitWithName:(NSString *)traitName andValue:(uint32_t)traitValue{
NSRange selectedRange = [txtViewNote selectedRange];
NSDictionary *currentAttributesDict = [txtViewNote.textStorage attributesAtIndex:selectedRange.location
effectiveRange:nil];
UIFont *currentFont = [currentAttributesDict objectForKey:NSFontAttributeName];
UIFontDescriptor *fontDescriptor = [currentFont fontDescriptor];
NSString *fontNameAttribute = [[fontDescriptor fontAttributes] objectForKey:UIFontDescriptorNameAttribute];
UIFontDescriptor *changedFontDescriptor;
if ([fontNameAttribute rangeOfString:traitName].location == NSNotFound) {
uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | traitValue;
changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
}
else{
uint32_t existingTraitsWithoutTrait = [fontDescriptor symbolicTraits] & ~traitValue;
changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithoutTrait];
}
UIFont *updatedFont = [UIFont fontWithDescriptor:changedFontDescriptor size:0.0];
NSDictionary *dict = #{NSFontAttributeName: updatedFont};
[txtViewNote.textStorage beginEditing];
[txtViewNote.textStorage setAttributes:dict range:selectedRange];
[txtViewNote.textStorage endEditing];
}
pragma mark - btnSave
-(IBAction)btnSave:(id)sender
{
NSURL *documentDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *documentURL = [documentDirectoryURL URLByAppendingPathComponent:#"test.html"];
NSString *htmlCode = txtViewNote.text;
NSError* error;
if (![htmlCode writeToURL:documentURL atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
NSLog(#"Couldn't save file because: %#", error);
}
NSString* fileToUpload = [NSString stringWithContentsOfURL:documentURL encoding:NSUTF8StringEncoding error:&error];
if (!fileToUpload) {
NSLog(#"Couldn't read file because: %#", error);
}
}
can any one html me?
The problem is you are saving the plain text of the textView instead of the attributedText.
NSString *htmlCode = txtViewNote.text;
Instead you should save the attributed text like this:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType,NSDocumentTypeDocumentAttribute, nil];
NSData *htmlData = [[self txtViewNote].attributedText dataFromRange:NSMakeRange(0, [self txtViewNote].attributedText.length) documentAttributes:attributes error:NULL];
NSString *htmlCode = [[NSString alloc]initWithData:htmlData encoding:NSUTF8StringEncoding];
If you want to write the htmlCode to the textView, you should:
NSMutableAttributedString *tmp = [[NSMutableAttributedString alloc] initWithData:htmlData options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
[txtViewNote setAttributedText:tmp];
In my json file I have a title, subtitle, and url.
I sort the title to set the items alphabetically, but the url isn't sorted with the title and I don't know why.
This is what i've done:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSArray *arrayOfItems = [allDataDictionary objectForKey:#"items"];
for (NSDictionary *diction in arrayOfItems) {
NSString *titles = [diction objectForKey:#"title"];
NSString *station = [diction objectForKey:#"url"];
[jsonArray addObject:titles];
[jsonStations addObject:station];
// SORT JSON
NSArray *sortedArray;
sortedArray = [jsonArray sortedArrayUsingComparator:^NSComparisonResult(NSString *title1, NSString *title2)
{
if ([title1 compare:title2] > 0)
return NSOrderedDescending;
else
return NSOrderedAscending;
}];
[jsonArray setArray:sortedArray];
What happens is, if I press the first item in the tableView, I get get the url from a total diffrent title. What should I do to get the title to match the url and title in the tableView?
Any help appreciated
EDIT: here's the tableView:didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == _currentRadio) {
return;
}
if(_radio) {
[_radio shutdown];
[_radio release];
_radio = nil;
}
[_statusLabel setText:#""];
[_titleLabel setText:#""];
_currentRadio = indexPath.row;
NSString *radioUrl = [jsonStations objectAtIndex:indexPath.row];
if([radioUrl hasPrefix:#"mms"]) {
_radio = [[MMSRadio alloc] initWithURL:[NSURL URLWithString:radioUrl]];
} else {
_radio = [[HTTPRadio alloc] initWithURL:[NSURL URLWithString:radioUrl]];
}
if(_radio) {
[_radio setDelegate:self];
[_radio play];
}
[self.tableview reloadData];
}
The code was placed wrong, another setup for the code, fixed the sorting problem.
I developed an App in xcode 4.2 that reads data from a phpMyAdmin database and loads it to a tableview. Now if I do the same inxcode 4.3, it doesn't work anymore. I am looking for a solution since days now, but can't find any and I have no idea why it doesn't work (my database and php script works fine).
FirstViewController.h:
NSMutableArray *myArray;
FirstViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
myArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions
error:&error];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [myArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *info = [myArray objectAtIndex:indexPath.row];
cell.textLabel.text = [info objectForKey:#"name"];
cell.detailTextLabel.text = [info objectForKey:#"Message"];
return cell;
}
I am using HTMLParser by Ben Reeves. It works great but the only problem is that I couldn't put the output in UITableView. Anyone can tell me what's wrong with this code? ...................................................................................
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError *error = nil;
NSURL *url=[[NSURL alloc] initWithString:#"http://website.com/"];
NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error];
if (error) {
NSLog(#"Error: %#", error);
return;
}
HTMLNode *bodyNode = [parser body];
NSArray *divNodes = [bodyNode findChildTags:#"div"];
for (HTMLNode *inputNode in divNodes) {
if ([[inputNode getAttributeNamed:#"class"] isEqualToString:#"views-field-title"]) {
NSLog(#"%#", [inputNode allContents]);
listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil];
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
#end
You're reinitializing your array every time you find a new element. I think you need to move
listData = [[NSArray alloc] initWithObjects:[inputNode allContents], nil];
outside of your loop and change it to
listData = [[NSMutableArray alloc] init];
listData should be an NSMutableArray so you can add data to it. You'll need to change this in your variable definition too.
Then inside your loop, use [listData addObject:[inputNode allContents]];
I'm very new to this, so pardon my ignorance.
I have the following method that I've pieced together and I get no errors when it's running, and I verified that I'm getting data from the web service. What I do notice is that when I put a breakpoint on the numberOfRowsInSection method it returns 0 both times. I assume that means I'm not loading my array correctly.
Declare my messages property in the header
#property (nonatomic, strong) NSArray *messages;
Synthesize that property in the m file
#synthesize messages;
This is the method that loads the data and is supposed to reload the table
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
if ([response isOK])
{
// Success! Let's take a look at the data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData: [[response bodyAsString] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:nil];
if([[result objectForKey:#"result"] isEqualToString:#"success"])
{
NSArray *message_array = [result objectForKey:#"messages"];
for(NSUInteger i = 0; i < [message_array count]; i++)
{
EHRXMessage *m = [[EHRXMessage alloc] init];
NSDictionary *message = [message_array objectAtIndex: i];
m.subject = [message objectForKey:#"Title"];
m.callback_name = [message objectForKey:#"CallbackName"];
[self.messages setValue:m forKey:[NSNumber numberWithInt:i]];
}
[self.tableView reloadData];
}
else
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Inbox Error!"
message:#"Error loading messages"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
And here is the method where I tell it how to load the cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MessageCell"];
EHRXMessage *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = message.callback_name;
cell.detailTextLabel.text = message.subject;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
And here's a snippet of what the json looks like
{"result":"success","count":"0", "messages":[{"SenderID":"6fcb7c19-b21f-4640-a237-0e7ac5ca0ce8","Title":"General","Message":"","CallbackName":"Claudia","CallbackNumber":"1295","EncounterID":null,"AdmissionID":"d7387243-3e8a-42e4-8a85-fdd3428dae68","DateSent":"3/9/2012 12:52 PM"}]}
- (void)viewDidLoad
{
[super viewDidLoad];
self.loaded = FALSE;
NSURL *URL = [NSURL URLWithString:#"http://46.136.168.166:8000/test.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
// creating loading indicator
self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
if(connection){
self.recievedData = [NSMutableData data];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
NSDictionary *item = [self.dataBase objectAtIndex:[indexPath section]];
NSArray *item_d = [item allKeys];
[[cell textLabel] setText:[item objectForKey:[item_d objectAtIndex:[indexPath row]]]];
return cell;
}
- (void)fetchedData:(NSMutableData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
[self setDataBase:[json objectForKey:#"json-data-header"]];
[self.table reloadData];
}
Do you have numberOfRowsInSection?
EDIT
Be sure to initialize the data source (self.messages)